翻译Ninject到ASP.NET MVC 6 DI [英] Translating Ninject to ASP.NET MVC 6 DI

查看:93
本文介绍了翻译Ninject到ASP.NET MVC 6 DI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图进入新的ASP.NET MVC 6东西,但我有一个非常艰难的时间与他们的新离子系统。我曾尝试在网上找到的资源,但一切我觉得只覆盖绝对是最最低限度使用它。

I am trying to get into the new ASP.NET MVC 6 stuff, but I'm having a very hard time with their new DI system. I have tried to find resources online, but everything I find covers only the absolute most bare minimum to use it.

我是previously使用 Ninject ,和我有几个线的UPS的工作是这样的:

I was previously using Ninject, and I have several wire-ups that work like this:

Bind<IDocumentStore>()
    .ToMethod(c => CreateDocumentStore())
    .InSingletonScope();

private static IDocumentStore CreateDocumentStore() {
    // lots of initialization code, etc.
    return documentStore;
}

但到目前为止,我有困难的时候找到了如何这种行为对微软的新系统的DI翻译的。所有我能找到像这样的例子:

But so far I am having a difficult time finding out how to translate this kind of behaviour to Microsoft's new DI system. All I can find are examples like this:

services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();

services.AddMvc();

这里的一切似乎是对目标服务的默认构造函数完全工作。有什么办法来产生,我在这个新的DI系统需要?行为

Where everything seems to work entirely on the default constructor for the target service. Is there any way to produce the behaviour I am needing in this new DI system?

我见过的

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

但我不是是否会做什么,我想,或者如果它被保留用于特定的行为真的很清楚。

But I'm not really clear on whether that will do what I am thinking, or if it is reserved for specific behaviours.

推荐答案

AddTransient 方法有不同的重载,其中一个接受一个lambda前pression:

The AddTransient method has various overloads, one of which accepts a lambda expression:

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

不过看来你是使用Ninject InSingletonScope() 改良剂所以这可能是比较合适的:

However it seems you are using the Ninject InSingletonScope() modifier so this may be more appropriate:

services.AddSingleton<IEmailSender>(s => CreateDocumentStore());

附加说明:有一些 pre -release文档使用(当然,这是不完整的,可能是不正确的,但可以帮助)

Additional note: There is some pre-release documentation available (of course, it's not complete and may be incorrect but may help)

这篇关于翻译Ninject到ASP.NET MVC 6 DI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆