在ASP.NET中使用Unity依赖注入 [英] Dependency Injection using Unity in ASP.NET

查看:143
本文介绍了在ASP.NET中使用Unity依赖注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个pretty直截了当设置。

 命名空间ObjectNamespace
{
    公共类CustomProcessor:ICustomProcessor<&myObject的GT;
    {
        公共CustomProcessorResult执行(myObject的数据)
        {
            尝试
            {
                VAR集装箱=​​新UnityContainer();
                // UnityConfigurationSection节=新UnityConfigurationSection();                VAR部分=(UnityConfigurationSection)ConfigurationManager.GetSection(团结);
                //这给Microsoft.P​​ractices.Unity.Configuration.UnityConfigurationSection
                section.Containers.Default.Configure(容器);                无功配置= Container.Resolve< ICustomProcessorConfiguration>();
                VAR的emailer = container.Resolve< IEmailManager>();
                VAR reportGenerator = container.Resolve< IReportGenerator>();
            }
            赶上(例外五)
            {
                Trace.WriteLine(它没有试图初始化DI其它的组件);
                扔;
            }

该错误消息是一个空引用异常。它显示,在

  section.Containers.Default.Configure(容器);

我的部分抛出我回我在web.config文件中的值是在该行(Microsoft.P​​ractices.Unity.Configuration.UnityConfigurationSection)评论

我在我无计可施只是为了实现这个Execute方法。我不知道为什么它给我空引用错误。容器应该由UnityConfigurationSection进行配置。

这是我里面的web.config文件中< configSections> 标签

 <节名称=团结TYPE =Microsoft.P​​ractices.Unity.Configuration.UnityConfigurationSection,myCustom.dll/>

据我知道这是如何解决并绑定到一个接口。难道我做错了什么?

有没有建立一个部分的任何其他方式?或配置容器?解决之前?

编辑:在下面我提供的一个答案试图跳过部分的$ C $的部分c,而DI组件仍然没有被因为它说,头的意见缺少初始化这就是它的看着在配置文件中。这是应用程序设置的方式。所以我猜从配置团结部分抓住价值是至关重要的。什么办法可以将我的code节的一部分?使其配置我的容器?

我已经映射到我的<团结> myApp.cfg 文件位置(如标签为DI:对电子邮件)

 <输入类型=myProject.Interfaces.IEmailManager,mySolution(DLL名称)
    mapTo =myProject.EmailManager,mySolution(DLL名称)>
<终身TYPE =单身/>
< /类型>

所以,另一项建议后,我去掉了所有的XML基于统一的集成code,我从Unity得到一个 ResolutionFailedException 。我已经采取了所有的XML集成和建议一样注册,但现在我得到一个建立操作失败,需要的属性,头注释未找到。我甚至有一个别名myApp.cfg设置为 ControlledLifetimeManager A typeAlias​​,我已经采取了太多。没有统一引用保持,这是我得到的错误。它试图从web.config行43阅读并给我这个错误。没有,需要头注释的,或者我所知道的任何注册。


解决方案

  

有没有建立一个部分的任何其他方式?或配置容器?解决之前?


是的。有没有必要使用XML配置,除非你的应用程序需要的组件将不会重新编译周围改变(这是不正常的情况下)。 XML配置现在大多认为是配置DI容器一种过时的方式。它是脆且耗时相比$ C $的c-基于配置以保持

您可以改用流利的API和/或的容器扩展程序配置您的组件。下面是一口流利的API的例子:

  //开始组成根
VAR集装箱=​​新UnityContainer();//这是相当于XML注册
// code,你在你的问题显示
container.RegisterType&所述; IEmailManager,EmailManager>(新ContainerControlledLifetimeManager());
//结束组成根IEmailManager emailManager = container.Resolve< IEmailManager>();

组成根源应在你的应用程序的入口点进行设置。在ASP.NET中,这将是在`的Global.asax文件的的Application_Start 事件。

当然,你需要去掉你已经设置了XML配置+你已经建立了统一,或者您可以从Unity得到错误试图加载那些元素。任何XML元素的code

其他信息:

http://blog.ploeh.dk/2011/07/28/CompositionRoot /

I have a pretty straight forward setup.

namespace ObjectNamespace
{
    public class CustomProcessor : ICustomProcessor<myObject>
    {
        public CustomProcessorResult Execute(myObject Data)
        {
            try
            {
                var container = new UnityContainer();
                // UnityConfigurationSection section = new UnityConfigurationSection();

                var section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
                // this gives Microsoft.Practices.Unity.Configuration.UnityConfigurationSection
                section.Containers.Default.Configure(container);

                var configuration = Container.Resolve<ICustomProcessorConfiguration>(); 
                var emailer = container.Resolve<IEmailManager>(); 
                var reportGenerator = container.Resolve<IReportGenerator>();  
            }
            catch (Exception e)
            {
                Trace.WriteLine("It failed while trying to initialize the DI componenets");
                throw;
            }

The error message is of a null reference exception . It's showing that at

section.Containers.Default.Configure(Container);

my section throws me back the value I had in the web.config file which is commented on that line (Microsoft.Practices.Unity.Configuration.UnityConfigurationSection)

I'm at my wits end just to implement this Execute method. I don't know why it's giving me an error for null reference. The Container is supposed to be configured by the UnityConfigurationSection.

This is my web.config file inside the <configSections> tag

<section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, myCustom.dll" />

As far as I know that's how to resolve and bind to an interface. Am I doing something wrong?

Are there any alternative ways of setting up a section? or configuring the container? before resolving it?

EDIT : After the one answer provided below I tried to skip the section portion of the code , but the DI components are still not being initialized as it says that the "header comments" are missing which is what it's looking at in the config files. That's the way the application is set up. So I'm guessing grabbing the value from the config "unity" section is essential . any way I can incorporate the section part in my code ? Make it configure my Containers ?

I have mapped my <unity> tags for DI in myApp.cfg file here ( eg: for the email )

<type type= "myProject.Interfaces.IEmailManager, mySolution (dll name)"
    mapTo="myProject.EmailManager,  mySolution (dll name)" >
<lifetime type="singleton"/>
</type>

So after another suggestion , I stripped out all the XML unity based integration code and I'm getting a ResolutionFailedException from Unity. I have taken down all the xml integration and registered like suggested but now I am getting a " build operation failed, Required attribute , 'header comment' not found". I even had an alias set up in myApp.cfg as a typeAlias for ControlledLifetimeManager and I've taken that out too. no unity references remain and this is the error I am getting. It's trying to read from web.config line 43 and giving me this error. There isn't any registration of header comment that is needed or that I know of.

解决方案

Are there any alternative ways of setting up a section? or configuring the container? before resolving it?

Yes. There is no need to use XML configuration unless your application requires components to be changed around without a recompile (which is not normally the case). XML configuration is now mostly considered to be an obsolete way to configure a DI container. It is brittle and time consuming to maintain compared to code-based configuration.

You can instead use the fluent API and/or container extensions to configure your components. Here is an example of the fluent API:

// Begin composition root
var container = new UnityContainer();

// This is the equivalent to the XML registration 
// code you show in your question 
container.RegisterType<IEmailManager, EmailManager>(new ContainerControlledLifetimeManager());
// End composition root

IEmailManager emailManager = container.Resolve<IEmailManager>();

The composition root should be set up at the entry point of your application. In ASP.NET that would be in the Application_Start event of the `Global.asax' file.

Of course, you will need to strip out any code that you have set up for XML configuration + any XML elements that you have set up for Unity or you may get errors from Unity trying to load those elements.

Additional information:

http://blog.ploeh.dk/2011/07/28/CompositionRoot/

这篇关于在ASP.NET中使用Unity依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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