如何按约定注册实现两个接口的类?

时间:2019-02-07 18:21:05

标签: unity-container

比方说,我有一个实现IFooIBar的类。我想按惯例在Unity中注册 类,以便可以通过IFooIBar注入它。有办法吗?

1 个答案:

答案 0 :(得分:0)

让我们从unity开始而不使用约定。在这种情况下,您想要注册实现并将其绑定到多个interface,您可能会执行以下操作:

container.Register(typeof(BarFoo), lifetime);
container.Register(typeof(IBar), typeof(BarFoo));
container.Register(typeof(IFoo), typeof(BarFoo));

使用约定的要点是存档这样的内容。该示例确实简化了,并试图指出应该做什么。假设类型是BarFoo,但是通常类型是在程序集内定义的每种类型,因此应该应用一些附加逻辑来检测多个interface实现。

container.RegisterTypes(
    AllClasses.FromAssemblies(Assembly.Load("AssemblyName")),
    type => new[] { typeof(BarFoo), typeof(IFoo), typeof(IBar) },
    WithName.Default,
    WithLifetime.Hierarchical);

重点是在interface旁边注册实现本身,然后interface将映射到实现。如果您不注册实现,则每个接口都将绑定到实现的单独实例。 IMO对TransiendLifetime来说是没有道理的...但是,您也可以调整每种类型的生存期。


n.b。就像展示如何实施

container.RegisterTypes(
    AllClasses.FromAssemblies(Assembly.Load("AssemblyName")),
    type => 
    {
        var types = WithMappings.FromAllInterfaces(type).ToList();
        if(!type.IsAbstract && type.GetInterfaces().Count() > 1) //more than one interface
        {
            types.Add(type);
        }
        return types;
    },
    WithName.Default,
    WithLifetime.Hierarchical);
相关问题