Autofac复杂案例

注册解析泛型接口

注册泛型接口的非泛型类:

builder.RegisterAssemblyTypes(typeof(IEventHandler<>).Assembly)
.Where(t => t.IsClass && t.GetInterfaces().Any(i=>i.IsGenericType && i.GetGenericTypeDefinition()==typeof(IEventHandler<>)))
.AsSelf()
.AsImplementedInterfaces();

解析泛型接口:

//获取IEventHandler Type
var eventHandlerType = typeof(IEventHandler<>).MakeGenericType(typeof(TEvent));//TEvent是泛型
var enumerableType = typeof(IEnumerable<>).MakeGenericType(eventHandlerType);
//解析
var eventHandlerInstances = Program.LIFETIME_SCOPE.Resolve(enumerableType) as IEnumerable;

 

动态解析服务:

    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);
        }
    }

 注册ServiceLocator,在EventBus中使用ServiceLocator解析服务,这样就可以只注入一个ServiceLocator,不需要注入多个服务:

builder.RegisterType().AsImplementedInterfaces().AsSelf();
            builder.Register(c => new EventBus.EventBus()
            {
                ServiceLocator = c.Resolve()
            }).AsImplementedInterfaces().AsSelf();

 

 

 

 

 

 

 

 

 

 

 

11

你可能感兴趣的:(Autofac复杂案例)