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

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

问题描述

我有一个简单的 .NET 项目,我想知道引导 Unity 的最佳方法是什么.我从一个带有一堆控制器的 WebApp 开始.这些控制器中的每一个都有自己的 Handler 类,控制器将实现委托给它.类似于以下内容:

public class UsersHandler : IUsers{IAuthenticationClient authenticationClient;ILogger 记录器;public UsersHandler(IAuthenticationClient authClient, ILogger logger) { ... }}

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

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

对于初学者,我创建了一个 Singleton 类,它可以作为这个项目的入口点,在那里我实例化 UnityContainer 并注册类型.

现在我有了这个工作,我开始想知道应该由谁来处理类型注册,也就是说,我的应用程序的组合根应该是什么.WebApp 将是首选,但这需要添加对XYZ"项目的引用,这感觉不对,因为它被业务层使用.

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

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

var logger = container.Resolve();

无论如何,这是一个好习惯吗?

解决方案

Like

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

为了解决businessData中的依赖,在Modelproject中加入这个接口

命名空间模型项目{公共接口 IXYZData{int GetData();}}

然后在类中实现接口

商业项目

使用模型项目;命名空间业务层{公共类业务数据{私人 IXYZData _data;公共业务数据(IXYZData 数据){this._data = 数据;}公共 int GetData(){返回 _data.GetData();}}}

对于 XYZ 项目

使用模型项目;命名空间 XYZ{公共类 XYZData:IXYZData{公共 int GetData(){返回 1;}}}

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

var container = new UnityContainer();container.RegisterType(new HierarchicalLifetimeManager());GlobalConfiguration.Configuration.DependencyResolver = new UnityResolver(container);

希望这有帮助,干杯

更新:

如果您想在另一个类中使用 businessData 类,您应该应用与我们在添加接口的 XYZData 类中所做的相同的结构.

命名空间模型项目{公共接口 IbusinessData{int GetData();}}

然后在类中添加接口继承

使用模型项目;命名空间业务层{公共类业务数据:IbusinessData{.....

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

container.RegisterType(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天全站免登陆