如何通过实现两个接口约定来注册类?

问题描述 投票:1回答:1

比方说,我有一个实现IFooIBar类。我想通过在统一惯例注册类,这样我可以通过两种IFooIBar注入它。有没有办法做到这一点?

unity-container
1个回答
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 ......但是,你必须调整每种类型的寿命以及可能性。


注:正如一个展示如何可以实现

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);
© www.soinside.com 2019 - 2024. All rights reserved.