2017-04-24 41 views
2

嗨,我正在爲我的應用程序DI使用Simple Injector。我保留了框架DI的默認DI。用Simple Injector和.Net Core註冊數據庫上下文

但我需要用SimpleInjector註冊DbContext。當我運行應用程序

container.Verify() 

提供了以下錯誤

ActivationException:類型UsersDbContext的構造函數包含參數名爲「選項」和未註冊類型DbContextOptions。請確保DbContextOptions已註冊,或者更改UsersDbContext的構造函數。

我與SimpleInjectore註冊的DbContext在功能SimpleInjectorConfig.InitializeContainer(app, _container)

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

我的啓動是

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

我知道問題與選項,但我不知道簡單注射器如何需要註冊到容器的默認連接字符串。這是可以傳遞給簡單注射器的東西嗎?或者我應該使用DbContextFactory將連接字符串傳遞給UserDbContext

回答

4

你需要告訴SimpleInjector如何實例化,這似乎與DbContextOptions類型參數的構造函數的UsersDbContext

變化如何通過使用Register方法採取委託(工廠)的超載註冊DbContext參數如下圖所示:

container.Register<DbContext>(() => { 
    var options = // Configure your DbContextOptions here 
    return new UsersDbContext(options); 
}); 
+0

這個答案的工作,是我問的答案,但最終我最終交叉佈線DbContext,因爲我已經將它添加到StartUp.cs中的默認DI容器中 –

+0

@JeffFinn你能展示一下你的「交叉佈線」解決方案的片段嗎? – Jeff

0

創建構造函數並將選項對象作爲依賴項傳遞。在DI中註冊選項。在OnConfiguring方法,你可以設置連接字符串:

public partial class FooContext : DbContext 
{ 
    private FooContextOptions _options; 

    public FooContext(FooContextOptions options) 
    { 
     _options = options; 
    } 

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) 
    { 
     optionsBuilder.UseNpgsql(_options.ConnectionString); 
    } 
} 
0

這不是答案,我問,但它是一個另類我結束了使用。也許這可能對未來其他人有用

我交叉連接了默認DI容器的DbContext。

container.Register(app.ApplicationServices.GetService<UsersDbContext>, Lifestyle.Singleton); 

看着我的DI配置後,我覺得這是一個更好的解決辦法,因爲我的DbContext是隻在一個地方登記。我很高興離開它,因爲我正在使用實體框架和身份。這兩個都註冊到默認的DI容器,我要註冊的框架依賴關係,他們需要訪問DbContext

+1

爲了能夠正常工作,請查看https://github.com/simpleinjector/SimpleInjector/issues/398#issuecomment-291058077 – DanMusk

相關問題