使用Autofac解析通用接口

时间:2016-12-21 10:36:19

标签: c# reflection autofac command-pattern

这些是我的课程:

   public interface ICommandDtc{
        string Command { get; set; }
        string Xml { get; set; }
    }
    public interface ICommandHandler<in TCommand>
        where TCommand : ICommandDtc
    {
        CommandResult Execute(TCommand command);
        Task<CommandResult> ExecuteAsync(TCommand command);
    }

    public class CommandResult
    {
        public string Description { get; set; }
        public int Code { get; set; }
    }

    public interface ICommandBus{
    Task<CommandResult> SubmitAsync<TCommand>(TCommand command) where TCommand : ICommandDtc;
    CommandResult Submit<TCommand>(TCommand command) where TCommand : ICommandDtc;
    }

    public class CommandBus : ICommandBus{
        private readonly ILifetimeScope _container;
        public CommandBus(ILifetimeScope scope){
            _container = scope;
        }
        public async Task<CommandResult> SubmitAsync<TCommand>(TCommand command)
            where TCommand : ICommandDtc{
            var commandHandler = _container.Resolve<ICommandHandler<TCommand>>();
            return await commandHandler.ExecuteAsync(command);
        }
        public CommandResult Submit<TCommand>(TCommand command)
            where TCommand : ICommandDtc
        {
        **//its worked**
            var commandHandler = _container.Resolve<ICommandHandler<IntegerationCommand>>();
        **//exception**
            var commandHandler2 = _container.Resolve<ICommandHandler<TCommand>>();
            return commandHandler2.Execute(command);
        }
    }

    public abstract class CommandBase<TCommand> : ICommandHandler<TCommand>
        where TCommand : ICommandDtc{
        public async Task<CommandResult> ExecuteAsync(TCommand command){
            var commandResult = new CommandResult();
            try{
                commandResult = await InternalExecuteAsync(command);
            }

            catch (Exception exp){

            }
            return commandResult;
        }
        public CommandResult Execute(TCommand command)
        {
            var commandResult = new CommandResult();
            try
            {
                commandResult =  InternalExecute(command);
            }
            catch (Exception exp)
            {
            }
            return commandResult;
        }

        protected abstract Task<CommandResult> InternalExecuteAsync(TCommand command);
        protected abstract CommandResult InternalExecute(TCommand command);
    }//sample class 1
    public class IntegerationCommandHandler : CommandBase<IntegerationCommand>
    {
        protected override Task<CommandResult> InternalExecuteAsync(IntegerationCommand command){
            throw new System.NotImplementedException();
        }
        protected override CommandResult InternalExecute(IntegerationCommand command){
            switch (command.Command) {
                case "SendDocument":
                    return SendDocument(command.Xml);
            }
            return new CommandResult {Code = 5,Description = ""};
        }
        private CommandResult SendDocument(string xml){
            throw new System.NotImplementedException();
        }
    }//sample class 2
 public class SocialOperationCommandHandler : CommandBase<SocialOperationCommand>
    {
        protected override Task<CommandResult> InternalExecuteAsync(SocialOperationCommand command){
            throw new System.NotImplementedException();
        }
        protected override CommandResult InternalExecute(SocialOperationCommand command){
            throw new System.NotImplementedException();
        }
    }

和我的Autofac:

public static IContainer InitializeBusiness()
{
    if (_lifetimeScope != null)
    {
        _lifetimeScope.Dispose();
        _lifetimeScope = null;
    }
    ConfigureAutoMapper();
    var builder = new ContainerBuilder();
    builder.RegisterType<Bootstrapper>().AsSelf();
    var assemblies = Assemblies.GetBusinessAssemblies.ToArray();
    builder.RegisterAssemblyTypes(assemblies).AsImplementedInterfaces();
    builder.RegisterAssemblyTypes(Assembly.GetAssembly(typeof(ICommandDtc))).Named<ICommandDtc>(x => x.Name);

    builder.RegisterType<AutoFacValidatorFactory>().As<IValidatorFactory>();

    _container = builder.Build();
    return _container;
}

我试图使用:

try
{
    var addFormDtc=new AddFormDtc {CommandName = "SendDocument",SiteCollectionName = "IntegerationCommand",Xml = "1"};
    var obj = _scope.ResolveNamed<ICommandDtc>(addFormDtc.SiteCollectionName);
    obj.Command = addFormDtc.CommandName;
    obj.Xml = addFormDtc.Xml;
    var commandBus = _scope.Resolve<ICommandBus>();
    return commandBus.Submit(obj);
}
catch (Exception ex){
    comandResult.Code = 0;
    comandResult.Description = ex.Message;
    return comandResult;
}

但我在这一行得到例外:

var commandHandler2 = _container.Resolve<ICommandHandler<TCommand>>();

当我手动尝试它的工作时:

var commandHandler = _container.Resolve<ICommandHandler<IntegerationCommand>>();

例外:

  

请求的服务   “JahadServices.Business.Services.Command.ICommandHandler`1 [[JahadServices.Business.Dtos.Command.ICommandDtc,   JahadServices.Business.Dtos,Version = 1.0.0.0,Culture = neutral,   PublicKeyToken = null]]'尚未注册。为了避免这种情况   例外,要么注册一个组件来提供服务,请检查   使用IsRegistered()进行服务注册,或使用   ResolveOptional()方法来解析可选的依赖项。

1 个答案:

答案 0 :(得分:0)

您正在尝试解析ICommandHandler<ICommandDtc>,但您只是从此

注册了ICommandHandler<IntegerationCommand>
 IntegerationCommandHandler : CommandBase<IntegerationCommand>

ICommandHandler<ICommandDtc>ICommandHandler<IntegerationCommand>是不同的类型。

更新

我采用了你原来的解决方案并做了以下事情: 将此commandBus.Submit(obj);替换为此

commandBus.GetType().GetMethod(nameof(ICommandBus.Submit))
    .MakeGenericMethod(obj.GetType())
    .Invoke(commandBus, BindingFlags.Public, null, new[] { obj},
     CultureInfo.CurrentCulture);

它有效:) 其他信息Calling generic method with a type argument known only at execution time

小解释。

当您调用泛型方法(Submit)时,此方法中的类型取决于变量指针类型。在您的情况下,您将IntegerationCommand实例存储在类型为ICommandDtc的变量中。 Soo,当你调用Submit(ibj)时,它就像Submit(ibj)。所以,这是最初的问题,你用一个错误的泛型参数调用了方法。我刚用反射用正确的通用参数(提交)调用提交。

commandBus.GetType()
.GetMethod(nameof(ICommandBus.Submit)) //<- getting Submit<> method
    .MakeGenericMethod(obj.GetType()) //<- set generic parameter, 
                                      // so now it Submit<IntegerationCommand> 
    .Invoke(commandBus, BindingFlags.Public, null, new[] { obj}, //<- invoke method
相关问题