Plugin Development for nop 4.1 get DbContext error "the requested service 'Microsoft.EntityFrameworkCore.DbContextOptions has not been registered"

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.
5 years ago
I want to develope a plugin. DbContext is :

    public DeliverySchedulingObjectContext()
        {

        }

        public DeliverySchedulingObjectContext(DbContextOptions<DeliverySchedulingObjectContext> options) : base(options)
        {
        }


        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.ApplyConfiguration(new OrderShippingMethodCapacityMappingMap());
            modelBuilder.ApplyConfiguration(new ShippingMethodCapacityMap());
            base.OnModelCreating(modelBuilder);
        }

        public virtual int ExecuteSqlCommand(RawSqlString sql, bool doNotEnsureTransaction = false, int? timeout = null, params object[] parameters)
        {
            using (var transaction = this.Database.BeginTransaction())
            {
                var result = this.Database.ExecuteSqlCommand(sql, parameters);
                transaction.Commit();

                return result;
            }
        }

        public string CreateDatabaseScript()
        {
            this.DropPluginTable(this.GetTableName<OrderShippingMethodCapacityMapping>());
            this.DropPluginTable(this.GetTableName<ShippingMethodCapacity>());


            return this.Database.GenerateCreateScript();
        }

        public void Install()
        {
            #region Create Tables

            var dbScript = CreateDatabaseScript();
            Database.ExecuteSqlCommand(dbScript);



            this.DropStoredProcedure(Constants.LoadAvailableDeliveryDateTimesStoredProcedureName);
            this.CreateStoredProcedure(Constants.LoadAvailableDeliveryDateTimesStoredProcedureName, Constants.LoadAvailableDeliveryDateTimesEncryptedStoredProcedureFileName);

        }

        public virtual new DbSet<TEntity> Set<TEntity>() where TEntity : BaseEntity
        {
            return base.Set<TEntity>();
        }

        public IEnumerable<TElement> SqlQuery<TElement>(string sql, params object[] parameters)
        {
            throw new NotImplementedException();
        }

        public void Uninstall()
        {
            this.DropPluginTable(this.GetTableName<OrderShippingMethodCapacityMapping>());
            this.DropPluginTable(this.GetTableName<ShippingMethodCapacity>());

            this.DropStoredProcedure(Constants.LoadAvailableDeliveryDateTimesStoredProcedureName);
        }


        public virtual string GenerateCreateScript()
        {
            return this.Database.GenerateCreateScript();
        }

        public IQueryable<TQuery> QueryFromSql<TQuery>(string sql) where TQuery : class
        {
            throw new NotImplementedException();
        }

        public IQueryable<TEntity> EntityFromSql<TEntity>(string sql, params object[] parameters) where TEntity : BaseEntity
        {
            throw new NotImplementedException();
        }



        public void Detach<TEntity>(TEntity entity) where TEntity : BaseEntity
        {
            throw new NotImplementedException();
        }


and dependency registrar :




            builder.RegisterType<ShippingMethodCapacityService>().As<IShippingMethodCapacityService>().InstancePerLifetimeScope();

            builder.RegisterType<OrderShippingMethodCapacityMappingService>().As<IOrderShippingMethodCapacityMappingService>().InstancePerLifetimeScope();



            builder.RegisterPluginDataContext<DeliverySchedulingObjectContext>("nop_object_context_orderfulfillment_deliveryscheduling");


            builder.RegisterType<EfRepository<OrderShippingMethodCapacityMapping>>()
                .As<IRepository<OrderShippingMethodCapacityMapping>>()
                .WithParameter(ResolvedParameter.ForNamed<IDbContext>("nop_object_context_orderfulfillment_deliveryscheduling"))
                .InstancePerLifetimeScope();

            builder.RegisterType<EfRepository<ShippingMethodCapacity>>()
                .As<IRepository<ShippingMethodCapacity>>()
                .WithParameter(ResolvedParameter.ForNamed<IDbContext>("nop_object_context_orderfulfillment_deliveryscheduling"))
                .InstancePerLifetimeScope();


but when open list of plugin from admin panel get this error:



ComponentNotRegisteredException: The requested service 'Microsoft.EntityFrameworkCore.DbContextOptions`1[[Resanehlab.Plugin.OrderFulfillment.DeliveryScheduling.Data.DeliverySchedulingObjectContext, Nop.Plugin.OrderFulfilment.DeliveryScheduling, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' has not been registered. To avoid this exception, either register a component to provide the service, check for service registration using IsRegistered(), or use the ResolveOptional() method to resolve an optional dependency.

Autofac.ResolutionExtensions.ResolveService(IComponentContext context, Service service, IEnumerable<Parameter> parameters)
5 years ago
The objectcontext and the dependencyregister seem ok. Can you please share your PluginDbStartup class which implement the INopStartup interface?
5 years ago
Hello hossein1

There is two constructor display in your code.

public DeliverySchedulingObjectContext(){
}

And

public DeliverySchedulingObjectContext(DbContextOptions<DeliverySchedulingObjectContext> options):base(options)
{
}

Used second one and delete first one constructor in the code it will be work.because on it when you open list that time found first constructor. So use second constructor method and remove first constructor method.

Thank you
Sagar kayasth
5 years ago
sina.islam wrote:
The objectcontext and the dependencyregister seem ok. Can you please share your PluginDbStartup class which implement the INopStartup interface?



I forget to impelement INopStartup interface

thanks
4 years ago
sina.islam wrote:
The objectcontext and the dependencyregister seem ok. Can you please share your PluginDbStartup class which implement the INopStartup interface?


I've also forgot to add PluginDbStartup. Thank you
4 years ago
Im having the exact same problem. In my case I create a payments plugin but I need to save some information in the local DB but appers the same issue 'has not been registered' and 'There is no constructor'. I add changes in the NopEngine.cs just like other fixed with this post of StackOverFlow

(if (type.IsSubclassOf(typeof(BasePlugin))) {
        return null;
    })

but ths errors persist. I create a BaseEntity PaymentMethodRecord, a service with his current Interface PaymentMethorRecordService and IPaymentRecordService and the ObjectContext. The only diference with the documentarion is that i have the basePlugin in the Processor but add all in the constructor and install and Unistall Methods. Here is the Dependency Injection Class:

public class DependencyRegistrar : IDependencyRegistrar
    {
        private const string CONTEXT_NAME = "nop_object_context_promerica_cybersource";

        

        public virtual void Register(ContainerBuilder builder, ITypeFinder typeFinder, NopConfig config)
        {
            builder.RegisterType<PaymentMethodRecordService>().AsSelf();

            //data context        
            builder.RegisterPluginDataContext<PaymentMethodRecordObjectContext>(CONTEXT_NAME);

            //override required repository with our custom context
            builder.RegisterType<EfRepository<PaymentMethodRecord>>()
            .As<IRepository<PaymentMethodRecord>>()
            .WithParameter(ResolvedParameter.ForNamed<IDbContext>(CONTEXT_NAME))
            .InstancePerLifetimeScope();
        }

        public int Order => 1;
    }

Hope some one see the mistake. The app starts well but when I try to enter to the Shopping Cart or the Admin area appers the problem.
This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.