简体   繁体   English

Autofac工厂用于静态方法

[英]Autofac factory for a static method

I have a component in my application with an interface that looks like this: 我的应用程序中有一个组件,其界面如下所示:

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

I need to construct these instances using a static method: 我需要使用静态方法构造这些实例:

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

This is problematic for my unit testing so I am instantiating with a delegate factory with Autofac: 这对我的单元测试来说是有问题的,所以我使用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(...);           
    }
}

I am registering in Autofac like so: 我正在注册Autofac,如下所示:

builder.Register<ILogger>(ctx => (uri, key) => ServiceProxy.Create<ILogger>(uri, key));
  • If I need to register 10 different interfaces in the same way, can I do it in one line with generics? 如果我需要以相同的方式注册10个不同的接口,我可以在一行中使用泛型吗?
  • Is there a way to do this without injecting Func and doing it more like Ninject.Extensions.Factory? 有没有办法在不注入Func的情况下执行此操作,并且更像Ninject.Extensions.Factory?

You can do what you want by implementing IRegistrationSource 您可以通过实施IRegistrationSource来执行您想要的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;
        }
    }
}

You would have to register it like this : 你必须这样注册:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM