0

我不知道如何用我的 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(...)在线。

4

1 回答 1

0

我是个白痴......客户端调用ReportProviderFactory<Experience>.Create<>()指定了不同的类型TReport

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

这意味着我的TReporton类型错误ExperienceReportBaseFactoryExperienceDetailsReportProvider因为客户端正在使用 . 它应该是:

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

public class ExperienceDetailsReportProvider : ReportProvider<Experience, ExperienceDetailsReport>
{
    public ExperienceDetailsReportProvider(IReportFactory<Experience, ExperienceDetailsReport> reportFactory) : base(reportFactory) { ... }
    ...
}
于 2012-01-09T21:05:05.680 回答