Bootstrapping Unity - 组合根位置 [英] Bootstrapping Unity - Composition Root location

查看:187
本文介绍了Bootstrapping Unity - 组合根位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的.NET项目,我想知道什么是最好的方法来引导Unity。
我开始用一个WebApp与一堆控制器。这些控制器中的每一个都具有自己的Handler类,控制器将对其进行委托。以下行:

  public class UsersHandler:IUsers 
{
IAuthenticationClient authenticationClient;
ILogger记录器

public UsersHandler(IAuthenticationClient authClient,ILogger logger){...}
}

在Global.asax的Application_Start方法中,我正在创建UnityContainer并注册类型。
有一个第二个项目(Class Library),它基本上是业务层。



我现在创建了一个新的类库(让我们称之为'XYZ')处理应用程序的不同责任。 DI也在这里使用。





对于初学者,我创建了一个Singleton类,它将作为此项目的入口点,实例化了UnityContainer和注册类型。



现在我有这个工作,我开始想知道谁应该处理类型注册,意思是应该是应用程序的Composition Root。 WebApp将是第一选择,但是这将需要添加对XYZ项目的引用,因为业务层使用该项目并不感觉正确。



1)组合根应该是一个引用WebApp和XYZ的新类库,并在我的WebApp的global.asax中初始化?
但是,这将导致循环依赖,因为此Bootstrapper项目将知道WebApp,反之亦然。



2)如果我需要解决XYZ项目中的依赖关系怎么办?目前我有一个UnityContainer类的实例,所以我可以这样做:



var logger = container.Resolve< ILogger>();



这是个好习惯吗?

解决方案

喜欢



作为组合根的WebApp应该引用解决方案中的所有项目。其余的项目只应参考ModelProject



要解决businessData中的依赖关系,请将此界面添加到Modelproject

 命名空间Modelproject 
{
public interface IXYZData
{
int GetData();
}
}

然后在类中实现接口



对于商业项目

 使用Modelproject; 
命名空间BusinessLayer
{
public class businessData
{
private IXYZData _data;
public businessData(IXYZData data)
{
this._data = data;
}

public int GetData()
{
return _data.GetData();
}
}
}

对于XYZ项目



 使用Modelproject; 
命名空间XYZ
{
public class XYZData:IXYZData
{
public int GetData()
{
return 1;
}
}
}

然后在global.asax在WebApp中,您将使用XYZData类来解析接口IXYZData。
通过Unity将是

  var container = new UnityContainer(); 
container.RegisterType< IXYZData,XYZData>(new HierarchicalLifetimeManager());
GlobalConfiguration.Configuration.DependencyResolver = new UnityResolver(container);

希望这有助于欢呼



更新:



如果要在另一个类中使用businessData类,应该应用与我们在添加的XYZData类中相同的结构一个界面。

 命名空间Modelproject 
{
public interface IbusinessData
{
int GetData();
}
}

然后将界面继承添加到类

 使用Modelproject; 
命名空间BusinessLayer
{
public class businessData:IbusinessData
{
.....

最后告诉Global.asax中的Unity容器来解析类的接口

  container.RegisterType< IbusinessData,businessData>(new HierarchicalLifetimeManager()); 

现在,在需要使用IbusinessData的每个类中,将它添加到类的构造函数中就像我们在businessData构造函数中一样,然后Unity将在运行时创建该类时确保注入所有依赖项。


I have a simple .NET project and I am wondering what's the best approach for bootstrapping Unity. I started with a WebApp with a bunch of controllers. Each of these controllers has its own Handler class to which the controller delegates the implementation. Something in the lines of:

public class UsersHandler : IUsers
{
    IAuthenticationClient authenticationClient;
    ILogger logger;

    public UsersHandler(IAuthenticationClient authClient, ILogger logger) { ... }       
}

In the Application_Start method of the Global.asax I am creating the UnityContainer and registering types. There's a second project (Class Library) which is basically the Business layer.

I now created a new class library (let's call it 'XYZ') for handling a different responsability of the application. DI is being used here as well.

For starters, I created a Singleton class which would serve as an entry point to this project where I instantiate the UnityContainer and register types.

Now that I have this working, I started to wonder who should handle the type registration, meaning, what should be the Composition Root of my application. The WebApp would be the first choice, but that would require adding a reference to the 'XYZ' project which does not feel right since this is used by the business layer.

1) Should the Composition root be a new class library referencing both the WebApp and 'XYZ' and initialized in the global.asax of my WebApp? However, that would cause a circular dependency since this Bootstrapper project would know the WebApp and vice versa.

2) What if I need to resolve a dependency in the 'XYZ' project? Currently I have an instance of the UnityContainer class so I am able to do this:

var logger = container.Resolve<ILogger>();

Is this a good practice anyway?

解决方案

Like this great answer said

"All components in an application should be composed as late as possible"

And by that you should compose them in the global.asax in the WebApp project. All of them (which basically answers the two questions).

The composition root is a place where all of the modules in your application get composed. In your case the WebApp will be that project and should therefore refer to all of the projects in your solution. The WebApp should refer to Business Layer, XYZ and all of the other projects that you add.

"However, that would cause a circular dependency.."

No, only the composition root refers to the projects in the solution.

But how does business layer and XYZ work with each other then?

They don't. The core principle of DIP is to be dependent of abstractions and to fully use the DIP in your solution you need to design the code correctly.

Let's say we have one class in business Layer project that have a dependecy on the XYZ project

using XYZ;
namespace BusinessLayer
{
    public class businessData
    {
        public int GetData()
        {
            var data = new XYZData(); //from the XYZ project
            return data
        }
    }
}

And this class in the XYZ project

namespace XYZ
{
    public class XYZData
    {
        public int GetData()
        {
            return 1;
        }
    }
}

Now we have the dependecy between the project BusinessLayer and XYZ. To solve this we need to make the businessData in the BusinessLayer depend on abstraction instead of details.

To do that we need to use Interfaces to get rid of the dependency between the classes and when that's taken care of we don't need the reference of XYZ in the BusinessLayer project as it's not in use anymore.

But where do we store the Interface?

For this you create a ModelProject which all projects in the solution will refer to. The ModelProject do not refer to anything as it's purpose is to only store the DTOs and Interfaces etc.

The references in the solution should then be as this (sorry for my paint skillz):

Where WebApp, being the composition root, should refer to all projects in the solution. The rest of the projects should only refer to ModelProject

To resolve the dependecy in businessData add this interface to the Modelproject

namespace Modelproject
{
    public interface IXYZData
    {
        int GetData();
    }
}

And then the implementation of the interface in the classes

For Business project

using Modelproject;
namespace BusinessLayer
{
    public class businessData
    {
        private IXYZData _data;
        public businessData(IXYZData data)
        {
            this._data = data;
        }

        public int GetData()
        {
            return _data.GetData();
        }
    }
}

And for XYZ project

using Modelproject;
namespace XYZ
{
    public class XYZData: IXYZData
    {
        public int GetData()
        {
            return 1;
        }
    }
}

Then in the global.asax in the WebApp you resolve the Interface IXYZData with the XYZData class. By Unity that would be

var container = new UnityContainer();
container.RegisterType<IXYZData, XYZData>(new HierarchicalLifetimeManager());
GlobalConfiguration.Configuration.DependencyResolver = new UnityResolver(container);

Hope this helps, cheers

Update:

If you want to use the businessData class in another class you should apply the same structure as we did on the XYZData class which is adding an Interface.

namespace Modelproject
{
    public interface IbusinessData
    {
        int GetData();
    }
}

Then add the interface inheritage to the class

using Modelproject;
namespace BusinessLayer
{
    public class businessData: IbusinessData
    {
    .....

And finally tell the Unity container in Global.asax to resolve the interface to the class

container.RegisterType<IbusinessData, businessData>(new HierarchicalLifetimeManager());

Now, in every class that you need to use the IbusinessData, add it in the constructor of the class like we did in the businessData constructor and then Unity will make sure to inject all dependencies when that class is being created at runtime.

这篇关于Bootstrapping Unity - 组合根位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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