从 StructureMap 到 Unity

From StructureMap to Unity

我一直在寻找答案,但找不到。我有一个项目使用 StructureMap 作为它的依赖容器,但现在我想尝试微软的统一。

但是,我找不到如何将这段代码转换为 unity:

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 中执行 scan 部分吗?

Unity Auto Registration. There is also a 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();

非库方式——使用反射

在您的项目中的某处包含此方法(可能在容器注册中 class)

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<>));