比方说,我有一个实现IFoo
和IBar
类。我想通过在统一惯例注册类,这样我可以通过两种IFoo
或IBar
注入它。有没有办法做到这一点?
让我们从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);