一个服务注册多个类
ContainerBuilder cb = new ContainerBuilder(); cb.RegisterType<EnglishHello>().Keyed<IHello>("EN"); cb.RegisterType<FrenchHello>().Keyed<IHello>("FR"); cb.RegisterType<HelloConsumer>().WithAttributeFiltering();//这行一定要加
一、使用[KeyFilter]特性解析正确的实例:
public class HelloConsumer { public HelloConsumer([KeyFilter("EN")] IHello helloService) { } }
二、或使用IIndex解析正确的实例:
public class HelloConsumer { public HelloConsumer(IIndex<string,IHello> index) { var helloService = index["EN"]; } }
三、[KeyFilter]是通过继承 ParameterFilterAttribute 来实现功能,我们可以自己写一个类继承ParameterFilterAttribute,可以更灵活解析:
public sealed class DependencyDBAttribute : ParameterFilterAttribute { public DependencyDBAttribute(string serviceKey, bool readOnly) { this.ServiceKey = serviceKey; this.ReadOnly = readOnly; } public string ServiceKey { get; } public bool ReadOnly { get; set; } public override object ResolveParameter(ParameterInfo parameter, IComponentContext context) { return context.ResolveKeyed<IDB>("slave"); //if (string.IsNullOrWhiteSpace(this.ServiceKey)) // return this.ReadOnly // ? context.ResolveKeyed("_slave", parameter.ParameterType, new NamedParameter("readOnly", true)) // : context.Resolve(parameter.ParameterType); //return this.ReadOnly // ? context.ResolveKeyed($"{this.ServiceKey}_slave", parameter.ParameterType, new NamedParameter("readOnly", true)) // : context.ResolveKeyed(this.ServiceKey, parameter.ParameterType); } } //--------------注入------------------- public class CommonService { public CommonService([DependencyDBAttribute("master", true)]IDB db) { } }
动态实例化(Func<B>)
可以让您有效地调用Resolve<T>()
。如果您需要创建给定服务的多个实例,或者您不确定是否需要服务并希望在运行时作出决定,请使用此关系类型。
参数实例化(Func<X,Y,B>)
注册解析泛型接口
注册泛型接口的非泛型类:
builder.RegisterAssemblyTypes(typeof(IEventHandler<>).Assembly) .Where(t => t.IsClass && t.GetInterfaces().Any(i=>i.IsGenericType && i.GetGenericTypeDefinition()==typeof(IEventHandler<>))) .AsSelf() .AsImplementedInterfaces();
解析泛型接口:
//获取IEventHandler<TEvent> Type var eventHandlerType = typeof(IEventHandler<>).MakeGenericType(typeof(TEvent));//TEvent是泛型 var enumerableType = typeof(IEnumerable<>).MakeGenericType(eventHandlerType); //解析 var eventHandlerInstances = IServiceLocator.GetService(enumerableType) as IEnumerable;
解析服务:
IServiceLocator放在框架的公共库中,ServiceLocator放在项目库中,ServiceLocator中可以使用不同容器实现服务解析
这样做的好处是不需要所有用到ILifeTimeScope的地方都引用Autofac的包
public interface IServiceLocator { object GetService(Type type); } public class ServiceLocator : IServiceLocator { private readonly ILifetimeScope _lifetimeScope; public ServiceLocator( ILifetimeScope lifetimeScope) { _lifetimeScope = lifetimeScope; } public object GetService(Type type) { return _lifetimeScope.Resolve(type); } }
...