我一直在寻找答案但却找不到答案。我有一个项目使用StructureMap作为它的依赖容器,但现在我想尝试微软的统一。
但是,我无法找到如何将这段代码转换为统一的代码:
ObjectFactory.Initialize(cfg =>
{
cfg.For<IViewFactory>().Use<DefaultViewFactory>();
cfg.Scan(scan =>
{
scan.TheCallingAssembly();
scan.ConnectImplementationsToTypesClosing(typeof(IViewBuilder<>)); scan.ConnectImplementationsToTypesClosing(typeof(IViewBuilder<,>));
});
});
我知道 cfg.For ... 部分只是调用 container.RegisterType(); 但是如何进行扫描参与Unity?
答案 0 :(得分:1)
查看Unity Auto Registration。还有Nuget package可供使用。
以下是如何使用的示例:
var container = new UnityContainer();
container
.ConfigureAutoRegistration()
.ExcludeAssemblies(a => a.GetName().FullName.Contains("Test"))
.Include(If.Implements<ILogger>, Then.Register().UsingPerCallMode())
.Include(If.ImplementsITypeName, Then.Register().WithTypeName())
.Include(If.Implements<ICustomerRepository>, Then.Register().WithName("Sample"))
.Include(If.Implements<IOrderRepository>,
Then.Register().AsSingleInterfaceOfType().UsingPerCallMode())
.Include(If.DecoratedWith<LoggerAttribute>,
Then.Register()
.As<IDisposable>()
.WithTypeName()
.UsingLifetime<MyLifetimeManager>())
.Exclude(t => t.Name.Contains("Trace"))
.ApplyAutoRegistration();
答案 1 :(得分:1)
非图书馆方式 - 使用反思
在项目的某个地方(可能在容器注册类中)包含此方法
public static void RegisterImplementationsClosingInterface(UnityContainer container, Assembly assembly, Type genericInterface)
{
foreach(var type in Assembly.GetExecutingAssembly().GetExportedTypes())
{
// concrete class or not?
if(!type.IsAbstract && type.IsClass)
{
// has the interface or not?
var iface = type.GetInterfaces()
.Where(i => i.IsGenericType && i.GetGenericTypeDefinition ()
== genericInterface).FirstOrDefault();
if(iface != null)
{
container.RegisterType(iface, type);
}
}
}
}
通话:
RegisterImplementationsClosingInterface(container, Assembly.GetCallingAssembly(), typeof(IViewBuilder<>));