asp.net-mvc - 将Ninject转换为ASP.NET MVC 6 DI

标签 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;
}

但是到目前为止,我仍然很难找到如何将这种行为转换为微软新的DI系统的方法。我所能找到的都是这样的例子:
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();

和:
services.AddMvc();

一切似乎都可以完全在目标服务的默认构造函数上运行的地方。在这个新的DI系统中,有什么方法可以产生我需要的行为?

我看过
services.Configure<TOptions>(options => {});

但是我不清楚这是否会满足我的想法,还是保留给特定的行为。

最佳答案

AddTransient方法具有多种重载,其中一种可以接受lambda表达式:

services.AddTransient<IDocumentStore>(s => CreateDocumentStore());

但是,似乎您正在使用Ninject InSingletonScope() 修饰符,因此这可能更合适:
services.AddSingleton<IEmailSender>(s => CreateDocumentStore());

附加说明:有一些pre-release documentation可用(当然,它不完整,可能不正确,但可能会有所帮助)

关于asp.net-mvc - 将Ninject转换为ASP.NET MVC 6 DI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31695194/

相关文章:

c# - 当我使用 ASP.NET MVC 5 在服务器上部署时出现 JSON 404 错误

asp.net-mvc - Entity Framework "Migrations Configuration"和 autofac

asp.net-core-mvc - Asp.net MVC 将复选框数据放入 bool 值列表中

c# - 在 asp.net mvc core 中绑定(bind)一个 Guid 参数

c# - 什么方式比较好 : make own wrapper for DbContext or use DbContext in Controller

Javascript 未启用

c# - 使用 ValidateAntiForgeryToken 自定义授权过滤器订单执行

asp.net-mvc - 简单注入(inject)器 2.6 中的 "An MVC filter provider has already been registered for a different Container instance."

java - 在java/kotlin中通过inject()将变量传递给类构造函数

java - 根据条件进行依赖注入(inject)