使用ASP.NET 5呼叫使用DI构造函数时解析依赖 [英] Resolve dependencies when calling constructor using DI with ASP.NET 5

查看:149
本文介绍了使用ASP.NET 5呼叫使用DI构造函数时解析依赖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该网站似乎充斥着关于如何使用DI与ASP.NET 5例子,但的例子并非个演示如何调用构造和依赖关系。

The web seems flooded with examples on how to use DI with ASP.NET 5 but not one of the examples shows how to call a constructor and resolve dependencies.

以下只是许多情况之一:
<一href=\"http://social.technet.microsoft.com/wiki/contents/articles/28875.dependency-injection-in-asp-net-vnext.aspx\" rel=\"nofollow\">http://social.technet.microsoft.com/wiki/contents/articles/28875.dependency-injection-in-asp-net-vnext.aspx

The following is just one of many cases: http://social.technet.microsoft.com/wiki/contents/articles/28875.dependency-injection-in-asp-net-vnext.aspx

但是,如果我想要做以下会发生什么:

But what happens if I want to do the following:

var todoRepository = app.ApplicationServices.GetRequiredService<ITodoRepository>();
ToDoController controller = new TodoController(todoRepository);

presumably这可以缩短到类似...

Presumably this can be shorted to something like...

.Get<TodoController>()

就像你可以在Ninject。

Like you can in Ninject.

有人能解释这可怎么办呢?

Can someone explain how this can be done?

推荐答案

首先,你要确保你要构建与DI容器注册的类。 (鉴于你控制器的例子,它可能已经是多亏了MVC框架。)

First, you'll want to make sure the class you want to construct is registered with the DI container. (Given your example of a controller, it probably already is thanks to the MVC framework.)

有多种的方式来做到这一点,其中最基本的是注册一个瞬间。请注意,这需要的 ConfigureServices 阶段做你的启动类。

There's several ways to do this, the most basic of which is registering a Transient. Note this needs to be done in the ConfigureServices stage of your Startup class.

services.AddTransient<ToDoController>();

一旦它注册,你可以解决它,就像使用任何其他服务:

Once you have it registered, you can resolve it just like you would any other service:

app.ApplicationServices.GetRequiredService<ToDoController>();

有关更多信息,我建议你的维克多Hurdugaci的依赖注入博客在ASP.NET vNext 。它是为阿尔法编写的,但它看起来像它仍然是准确的。

For more information, I'd recommend Victor Hurdugaci's blog on Dependency Injection in ASP.NET vNext. It was written for alpha, but it looks like it's still accurate.

这篇关于使用ASP.NET 5呼叫使用DI构造函数时解析依赖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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