如何从container.ComponentRegistry.Registrations
中获取用于在容器中注册类的类型?
// I have some types like
interface IBase { }
interface IA : IBase { }
interface IB : IBase { }
class A : IA { }
class B : IB { }
class Program
{
static void Main(string[] args)
{
var builder = new ContainerBuilder();
// Registering types as interface implementations
builder.RegisterType<A>().As<IA>();
builder.RegisterType<B>().As<IB>();
var c = builder.Build();
// Trying to get all registered types assignable to IBase
var types = c.ComponentRegistry.Registrations
.Where(r => typeof(IBase).IsAssignableFrom(r.Activator.LimitType))
.Select(r => r.Activator.LimitType); // Returns A insted of IA
// Trying to Resolve all types
types.Select(t => c.Resolve(t) as IBase).ToList();
}
}
因为.Activator.LimitType
返回了在容器中使用的A
类型的IA
插入,我得到了异常
Autofac.Core.Registration.ComponentNotRegisteredException : The requested service 'A' has not been registered. To avoid this exception, either register a component to provide the service, check for service registration using IsRegistered(), or use the ResolveOptional() method to resolve an optional dependency.
一种方法是确保您的寄存器A
不仅针对IA
,还针对also针对IBase
(与B
相同)。
然后解析IEnumerable<IBase>
将同时找到A
和B
:
using System;
using System.Collections.Generic;
using System.Linq;
using Autofac;
namespace WatCode
{
interface IBase { }
interface IA : IBase { }
interface IB : IBase { }
class A : IA { }
class B : IB { }
class Program
{
static void Main(string[] args)
{
var builder = new ContainerBuilder();
// Registering types as interface implementations
builder.RegisterType<A>().AsImplementedInterfaces(); // register against IA and IBase
builder.RegisterType<B>().AsImplementedInterfaces(); // register against IB and IBase
var c = builder.Build();
var matching = c.Resolve<IEnumerable<IBase>>();
Console.WriteLine(matching.Count());
}
}
}
由于上面找到了两个匹配项,因此上面将2
写入控制台。