如何使用Unity容器解析的通用接口作为构造函数参数解析通用类

时间:2012-01-09 19:18:33

标签: generics dependency-injection unity-container ioc-container service-locator

我无法弄清楚如何注册一个与我的Unity(2.0)容器有一个注入通用接口的通用抽象类。这是界面和类:

public interface IReportFactory<in TEntity, out TReport>
{ ... }

public class ExperienceReportBaseFactory :
    IReportFactory<Experience, ExperienceReportBase>
{ ... }

public abstract class ReportProvider<TEntity, TReport>
{
    protected ReportProvider(
        IReportFactory<TEntity, TReport> reportFactory)
    { ... }
    ...
}

public class ExperienceDetailsReportProvider
    : ReportProvider<Experience, ExperienceReportBase>
{
    public ExperienceDetailsReportProvider(
        IReportFactory<Experience, ExperienceReportBase>
        reportFactory)
        : base(reportFactory) { ... }
    ...
}

这是注册码:

Container.RegisterInstance(typeof(IReportFactory<Experience, ExperienceReportBase>), new ExperienceReportBaseFactory())
         .RegisterType(typeof(ReportProvider<Experience, ExperienceReportBase>),
             typeof (ExperienceDetailsReportProvider),
             new InjectionConstructor(Container.Resolve(typeof (IReportFactory<Experience, ExperienceReportBase>))));

这是我的提供商工厂尝试解析ReportProvider<,>

public class ReportProviderFactory<TEntity> : IReportProviderFactory<TEntity>
{
    private readonly IServiceLocator _serviceLocator;

    public ReportProviderFactory(IServiceLocator serviceLocator)
    {
        _serviceLocator = serviceLocator;
    }

    public ReportProvider<TEntity, TReport> Create<TReport>()
        where TReport : ActiveReport
    {
        var reportProvider =
            _serviceLocator.GetService(typeof (ReportProvider<TEntity, TReport>)) as
                ReportProvider<TEntity, TReport>;
        return reportProvider;
    }
}

我知道,“无法构造类型ReportProvider`2。您必须在_serviceLocator.GetService(...)行上配置容器以提供此值。

1 个答案:

答案 0 :(得分:0)

我是个白痴......呼叫ReportProviderFactory<Experience>.Create<>()的客户正在为TReport指定不同的类型:

var reportProvider = _reportProviderFactory<Experience>.Create<ExperienceDetailsReport>();

这意味着TReportExperienceReportBaseFactory上的ExperienceDetailsReportProvider类型错误,因为正在使用的客户端。它应该是:

public class ExperienceReportBaseFactory : IReportFactory<Experience, ExperienceDetailsReport> { ... }

public class ExperienceDetailsReportProvider : ReportProvider<Experience, ExperienceDetailsReport>
{
    public ExperienceDetailsReportProvider(IReportFactory<Experience, ExperienceDetailsReport> reportFactory) : base(reportFactory) { ... }
    ...
}