Register a DB Context with Simple Injector and .Net Core c# entity-framework-core simple-injector


Hi I'm using Simple Injector for my application DI. I have kept the default DI for framework DI.

But I need to register the DbContext with SimpleInjector. When I run the application


Gives the following error

ActivationException: The constructor of type UsersDbContext contains the parameter with name 'options' and type DbContextOptions that is not registered. Please ensure DbContextOptions is registered, or change the constructor of UsersDbContext.

I'm registering the DbContext with SimpleInjectore in a function SimpleInjectorConfig.InitializeContainer(app, _container)

// DbContext
container.Register<DbContext, UsersDbContext>();

And my Startup is

public void ConfigureServices(IServiceCollection services)
    var conString = Configuration.GetConnectionString("DefaultConnection");

    // Add framework services.
    services.AddDbContext<UsersDbContext>(options => options.UseSqlServer(conString));

    services.AddIdentity<User, IdentityRole>()



    // Add application services
    services.AddSingleton<IControllerActivator>(new SimpleInjectorControllerActivator(_container));
    services.AddSingleton<IViewComponentActivator>(new SimpleInjectorViewComponentActivator(_container));


public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    SimpleInjectorConfig.InitializeContainer(app, _container);




I know the problem is with the options, but I don't know how Simple Injector needs the default Connection string registered to the container. Is this something that can be passed to Simple Injector ? or should I use the DbContextFactory to pass the connection string to UserDbContext ?

10/3/2017 5:09:35 PM

Accepted Answer

You need to tell SimpleInjector how to instantiate the UsersDbContext which seems to have a constructor with the parameter of type DbContextOptions.

Change how you register your DbContext by using an overload of Register method that take a delegate (factory) parameter like below:

container.Register<DbContext>(() => {
    var options = // Configure your DbContextOptions here
    return new UsersDbContext(options);
1/23/2018 2:24:52 PM

Popular Answer

All answers don't work for me, but I found another approach.


It works

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow