在泛型类中注入依赖项时出错

时间:2019-06-26 11:50:01

标签: c# dependency-injection

我有一个类和通用接口,在尝试注入错误时会发生:

  

System.ArgumentException:'无法实例化实现类型   'Application.Process.ProcessIntegrationUseCase.GenericClass.HandlerManager app.post("/hi/:download", function (req, res) { var download = req.params.download; res.download("./uploads/"+download+""); }); 1 [T]'。'

1[T]'
  for service type
  'Application.Process.ProcessIntegrationUseCase.GenericClass.IHandlerManager

接口IHandlerManager

namespace Application.Process.ProcessIntegrationUseCase.GenericClass
{
    public abstract class HandlerManager<T>: IHandlerManager<T> 
    {
        protected IHandlerManager<T> sucessor;

        public void SetSucessor(IHandlerManager<T> sucessor)
        {
            this.sucessor = sucessor;

        }

        public abstract void ProcessRequest(T request);
     }
}

去势注射

namespace Application.Process.ProcessIntegrationUseCase.GenericClass
{
    public interface IHandlerManager<T> 
    {
        void SetSucessor(IHandlerManager<T> sucessor);

        void ProcessRequest(T request);

    }
}

调用注入HandlerManager的代码

public void Register(IServiceCollection services)
{

   // Injection History Use Cases Application


   services.AddTransient(typeof(IHandlerManager<>),
   typeof(HandlerManager<>));


}

在HandlerManager中重写方法的类

using Domain.Meta;
using System;
using Microsoft.Extensions.Logging;
using Application.Process.ProcessIntegrationUseCase.GenericClass;

namespace Application.UseCases.Process.ProcessIntegrationUseCase.Habitacional
{
    public sealed class ProcessHabitacionalUseCase : IProcessHabitacionalUseCase
    {
        private readonly StartProcessHandler<HistoryHabitacional> _startProcessHandler;

        private readonly ILogger _iLogger;

        public ProcessHabitacionalUseCase(ILogger iLogger,
                                    StartProcessHandler<HistoryHabitacional> startProcessHandler)

        {
            _iLogger = iLogger;

            _startProcessHandler = startProcessHandler;

        }

        public void Execute(HistoryHabitacional history)
        {
            if (history == null)
                throw new ArgumentNullException();

            try
            {              

               _startProcessHandler.ProcessRequest(history);

            }
            catch (Exception ex)
            {

                throw ex;
            }

        }
     }

}

1 个答案:

答案 0 :(得分:1)

您不能使用这种通用类型。 AddTransient()期望可以将指定的第二种类型的实例分配给对第一种类型的引用。通用HandlerManager<>无法分配给IHandlerManager<>;您需要指定隐式类型,并以一致的方式进行操作。

此外,HandlerManager<T>是抽象的,您无法创建它的实例。