我有一个使用 Unity 的项目,我观看了有关 StructureMap 的视频,我从一开始就喜欢注册的想法。
所以我创建了以下界面:
/// <summary>
/// An interface which must be implemented to create a configurator class for the UnityContainer.
/// </summary>
public interface IUnityContainerConfigurator
{
/// <summary>
/// This method will be called to actually configure the container.
/// </summary>
/// <param name="destination">The container to configure.</param>
void Configure(IUnityContainer destination);
}
并让程序集提供默认的 Configurator 类。我们还使用静态类包装了 Unity IoC,以便我们可以调用IoC.Resolve<T>
,我刚刚在该包装器中添加了以下函数:
/// <summary>
/// Configure the IoC
/// </summary>
public static class Configure
{
/// <summary>
/// Configure the IoC using by calling the supplied configurator.
/// </summary>
/// <typeparam name="TConfigurator">The configurator to use</typeparam>
public static void From<TConfigurator>() where TConfigurator : IUnityContainerConfigurator, new()
{
From(new TConfigurator());
}
/// <summary>
/// Configure the IoC using by calling the supplied configurator.
/// </summary>
/// <param name="configurationInterface">The configurator instance to use</param>
public static void From(IUnityContainerConfigurator configurationInterface)
{
configurationInterface.Configure(instance);
}
// other configuration.
}
因此,在程序或网站的初始化表单中,我只需调用:
IoC.Configure.From<BLL.DefaultMapping>();
在 BLL 中有这样一个类:
public class DefaultMapping:IUnityContainerConfigurator
{
public void Configure(IUnityContainer destination)
{
destionation.RegisterType<IRepository, SQLRepository>();
// and more..
}
}
唯一的缺点是你所有的层都耦合到所选的 IoC 容器。
更新:自从有了这个答案,我在我的博客上发布了一篇包含Unity 包装器的文章。