Cie*_*iel 9 asp.net-mvc dependency-injection asp.net-core-mvc
我试图进入新的ASP.NET MVC 6的东西,但我很难用他们的新DI系统.我试图在线查找资源,但我找到的所有内容仅涵盖使用它的绝对最低限度.
我之前使用的是Ninject,我有几个这样工作的连线:
Bind<IDocumentStore>()
.ToMethod(c => CreateDocumentStore())
.InSingletonScope();
private static IDocumentStore CreateDocumentStore() {
// lots of initialization code, etc.
return documentStore;
}
Run Code Online (Sandbox Code Playgroud)
但到目前为止,我很难找到如何将这种行为转化为微软的新DI系统.我能找到的只是这样的例子:
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
Run Code Online (Sandbox Code Playgroud)
和:
services.AddMvc();
Run Code Online (Sandbox Code Playgroud)
一切似乎完全在目标服务的默认构造函数上工作.有没有办法在这个新的DI系统中产生我需要的行为?
我见过了
services.Configure<TOptions>(options => {});
Run Code Online (Sandbox Code Playgroud)
但我不清楚这是否会影响我的想法,或者它是否留给特定的行为.
该AddTransient方法具有各种重载,其中一个重载接受lambda表达式:
services.AddTransient<IDocumentStore>(s => CreateDocumentStore());
Run Code Online (Sandbox Code Playgroud)
但是,您似乎正在使用Ninject InSingletonScope()修饰符,因此这可能更合适:
services.AddSingleton<IEmailSender>(s => CreateDocumentStore());
Run Code Online (Sandbox Code Playgroud)
附加说明:有一些预发布文档可用(当然,它不完整,可能不正确但可能有帮助)