Search code examples
c#asp.net-coreentity-framework-coresimple-injector

Register a DB Context with Simple Injector and .Net Core


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

container.Verify()

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>()
            .AddEntityFrameworkStores<UsersDbContext>()
            .AddDefaultTokenProviders();

    IdentityConfigurationService.ConfigureIdentityOptions(services);

    services.AddMvc();

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

    services.UseSimpleInjectorAspNetRequestScoping(_container);
}

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

    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    _container.Verify();

    app.UseMvc();
}

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 ?


Solution

  • 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);
    });