带有接口和具体类型参数的工厂注入

Factory injection with interface and concrete type parameter

我有以下界面并且class

public interface IService{};
public class ServiceImp:IService {};

我有以下 class 使用该服务的 es

public class ServiceProvider
{
   public ServiceProvider(Func<double, IService> service, double age)
   {
   }
}

public class ServiceProviderB
{
   public ServiceProviderB(Func<double, ServiceImp> service, double age)
   {
   }
}

我现在注册IServiceServiceImp的方式是这样的:

builder.Register<Func<double, IService>>(c=> age => new ServiceImp (age));
builder.Register<Func<double, ServiceImp >>(c=> age => new ServiceImp (age));

我不喜欢它,因为在我看来它像是双重工作。我知道如何使用 AsSelf()AsImplementedInterfaces() 来注册实际实例 ,这样我就只有 1 个注册声明,而不是两个。但在这种情况下,我处理的是函子,而不是实际的类型实例。

如何注册Autofac才能将上面的两个Register语句合并为一个?

答案是让Autofac使用the built-in relationship types而不是注册你自己的函数。

public class UnitTest1
{
    [Fact]
    public void Repro()
    {
        var builder = new ContainerBuilder();

        // Just register the type, not functions.
        builder.RegisterType<Implementation>().AsSelf().AsImplementedInterfaces();
        var container = builder.Build();

        // Autofac will handle creation of the Func<T> factories.
        var interfaceFactory = container.Resolve<Func<double, IService>>();
        var implementationFactory = container.Resolve<Func<double, Implementation>>();

        // Profit!
        var service = interfaceFactory(12);
        Assert.Equal(12, service.Age);

        var impl = implementationFactory(24);
        Assert.Equal(24, impl.Age);
    }

    public interface IService
    {
        double Age { get; }
    }

    public class Implementation : IService
    {
        public Implementation(double age)
        {
            this.Age = age;
        }
        public double Age { get; }
    }
}