[英]How to get a type from Autofac Registrations used for registration
如何从container.ComponentRegistry.Registrations
获取用于在容器中注册 class 的类型?
// 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
返回容器中使用的IA
类型A
类型,所以我得到一个异常
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
,而且针对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
写入控制台,因为它找到了两个匹配项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.