Autofac工厂用于静态方法

时间:2016-07-26 14:47:01

标签: c# dependency-injection autofac

我的应用程序中有一个组件,其界面如下所示:

interface ILogger : IService
{
    Task LogAsync(Message message);
}

我需要使用静态方法构造这些实例:

ILogger logger = ServiceProxy.Create<ILogger>(new Uri(...), new ServicePartitionKey(...));

这对我的单元测试来说是个问题,所以我使用Autofac代理工厂进行实例化:

public class LogConsumer
{
    private Func<Uri, ServicePartitionKey, ILogger> _logFactory;
    public LogConsumer(Func<Uri, ServicePartitionKey, ILogger> logFactory)
    {
        _logFactory = logFactory;
    }

    public async Task MethodThatUsesLogger()
    {
        ILogger logger = _logFactory(new Uri(...), new ServicePartitionKey(...));

        await logger.LogAsync(...);           
    }
}

我正在注册Autofac:

builder.Register<ILogger>(ctx => (uri, key) => ServiceProxy.Create<ILogger>(uri, key));
  • 如果我需要以相同的方式注册10个不同的接口,我可以在一行中使用泛型吗?
  • 有没有办法在不注入Func的情况下执行此操作,并且更像Ninject.Extensions.Factory?

1 个答案:

答案 0 :(得分:3)

您可以通过实施IRegistrationSource

来执行您想要的操作
class FactoryRegistrationSource<TService> : IRegistrationSource
{

    public Boolean IsAdapterForIndividualComponents
    {
        get
        {
            return false;
        }
    }

    public IEnumerable<IComponentRegistration> RegistrationsFor(Service service, Func<Service, IEnumerable<IComponentRegistration>> registrationAccessor)
    {
        IServiceWithType typedService = service as IServiceWithType;
        if (typedService == null)
        {
            yield break;
        }

        if (typedService.ServiceType == typeof(TService))
        {
            IComponentRegistration registration = RegistrationBuilder.ForDelegate<Func<Uri, TService>>((c, p) => ((Uri uri) => Factory.Get<TService>(uri)))
                                                                     .CreateRegistration();

            yield return registration;
        }
    }
}

你必须这样注册:

builder.RegisterSource(new FactoryRegistrationSource<ILogger>());