将依赖注入工厂

时间:2018-01-09 14:34:30

标签: c# dependency-injection autofac factory

刚开始使用Autofac&我不知道如何处理我正确击中的情况。我有一个工厂,我传回的类型依赖于我使用autofac注入的接口。以下是我遇到问题的特定组件的autofac配置:

builder.RegisterType<EmployerFunctions>().As<IEmployerFunctions>();

这是一家我遇到问题的工厂:

public static IMetaDataSaver GetMetaDataFactory(HttpRequestMessage request)
{
    if (request.IsReciprocal())
    {
        return new ReciprocalMetaDataSaver();
    }
    else
    {
        return new EmployerMetaDataSaver(); //<--error is here
    }
}

EmployerMetaDataSaver()的构造函数传递了IEmployerFunctions。我当然可能很懒,并且新建EmployerFunctions但是我不想这样做。

1 个答案:

答案 0 :(得分:0)

您可以为IMetaDataSaver个对象创建delegate factory

builder.RegisterType<EmployerFunctions>().As<IEmployerFunctions>();
builder.Register<Func<HttpRequestMessage, IMetaDataSaver>>(delegate(IComponentContext context)
    {
        if (request.IsReciprocal())
        {
            return new ReciprocalMetaDataSaver();
        }
        else
       {
           IComponentContext cc = context.Resolve<IComponentContext>();
           var functions = cc.Resolve<IEmployerFunctions>();
           return new EmployerMetaDataSaver(functions); //<--error is here
       }
    });

如果您需要为IMetaDataSaver创建HttpRequestMessage,则可以解析委托工厂并使用具体的HttpRequestMessage对象调用它:

// example with the explicit use container. Use DI instead in real code
Func<HttpRequestMessage, IMetaDataSaver> factory = container.Resolve<Func<HttpRequestMessage, IMetaDataSaver>>();
var dataSaver = factory(requestMessage);

此外,您可以使用普通工厂和DI:

builder.RegisterType<EmployerFunctions>().As<IEmployerFunctions>();
builder.RegisterType<MetaDataSaverFactory>().As<IMetaDataSaverFactory>();

工厂类看起来像下一个:

public interface IMetaDataSaverFactory
{
    IMetaDataSaver GetMetaDataFactory(HttpRequestMessage request);
}

public class MetaDataSaverFactory : IMetaDataSaverFactory
{
    private IEmployerFunctions _functions;
    public MetaDataSaverFactory(IEmployerFunctions functions)
    {
        _functions = functions;
    }

    public static IMetaDataSaver GetMetaDataFactory(HttpRequestMessage request)
    {
        if (request.IsReciprocal())
        {
            return new ReciprocalMetaDataSaver();
        }
        else
        {
            return new EmployerMetaDataSaver(_functions); 
        }
    }
}