如何使用自定义工厂方法注册开放通用



tl; dr :我可以使用autoFac创建一个通用工厂,以便我可以注入IProduct<TModel>而不是从任何需要的地方从IFactory解析它吗?有没有办法将解决问题的解决方案移至组成根?

因此,我正在使用第三方库,该库揭示了通过工厂创建的一些通用接口。出于演示目的,我们假设以下代码是库:

第三方库模型

public interface IFactory
{
    IProduct<TModel> CreateProduct<TModel>(string identifier);
}
internal class Factory : IFactory
{
    private readonly string _privateData = "somevalues";
    public IProduct<TModel> CreateProduct<TModel>(string identifier)
    {
        return new Product<TModel>(_privateData, identifier);
    }
}
public interface IProduct<TModel>
{
    void DoSomething();
}
internal sealed class Product<TModel>: IProduct<TModel>
{
    private readonly string _privateData;
    private readonly string _identifier;
    public Product(string privateData, string identifier)
    {
        _privateData = privateData;
        _identifier = identifier;
    }
    public void DoSomething()
    {
        System.Diagnostics.Debug.WriteLine($"{_privateData} + {_identifier}");
    }
}

我的代码

和我的TModel

public class Shoe { }

现在,假设我想要MyService中的IProduct<Shoe>。我需要在那里解决它:

public class MyService
{
    public MyService(IFactory factory)
    {
        IProduct<Shoe> shoeProduct = factory.CreateProduct<Shoe>("theshoe");
    }
}

,但是如果我能这样声明鞋子,那会更好:

public class ProductIdentifierAttribute : System.Attribute
{
    public string Identifier { get; }
    public ProductIdentifierAttribute(string identifier)
    {
        this.Identifier = identifier;
    }
}
[ProductIdentifier("theshoe")]
public class Shoe { }

然后这样注入?:

public class MyService
{
    public MyService(IProduct<Shoe> shoeProduct) { }
}

使用AutoFac我可以使用工厂来创建常规的非类别类,例如:

builder
    .Register<INonGenericProduct>(context =>
    {
        var factory = context.Resolve<INonGenericFactory>();
        return factory.CreateProduct("bob");
    })
    .AsImplementedInterfaces();

,但这对于通用类不起作用。我必须使用RegisterGeneric。不幸的是,您传递给RegisterGeneric的类型是Open Concrete 类型,而不是Open 接口类型。我想出了两个解决方法。

解决方案1 :反射IFactory提取_privateData(在实际库中,这有些复杂,涉及访问其他internal方法和类等(,然后将其作为OnPreparing中的autoFac参数提供:

Type factoryType = typeof(Factory);
Type factoryField = factoryType.GetField("_privateData", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Getfield);
Type productType = typeof(Product); // this is `internal` in the third party library, so I have to look it up from the assembly in reality
builder
.RegisterGeneric(productType)
.OnPreparing(preparing =>
{
    var factory = preparing.Context.Resolve<IFactory>();
    var privateFieldValue = factoryField.GetValue(factory);
    var closedProductType = preparing.Component.Activator.LimitType;
    var productModel = closedProductType.GetGenericArguments().Single();
    var productIdentifier = productModel.GetGenericArgument<ProductIdentifierAttribute>().Identifier;
    preparing.Parameters = new List<Parameter>()
    {
        new PositionalParameter(0, privateFieldValue),
        new PositionalParameter(0, productIdentifier)
    };
})
.AsImplementedInterfaces();

,但显然这是一个可怕的解决方案,原因很大,最重要的是它容易受到库内的内部变化的影响。

解决方案2 :创建一个虚拟类型并在OnActivating中替换它:

public class DummyProduct<TModel> : IProduct<TModel>
{
    public void DoSomething() => throw new NotImplementedException("");
}

因此,我们将其注册为打开通用,并在注入它之前替换其值:

MethodInfo openProductBuilder = this.GetType().GetMethod(nameof(CreateProduct), BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.InvokeMethod);
builder
    .RegisterGeneric(typeof(DummyProduct<>))
    .OnActivating(activating => 
    {
        var productModel = activating.Instance.GetType().GetGenericArguments().First();
        var productIdentifier = productModel.GetGenericArgument<ProductIdentifierAttribute>().Identifier;
        var factory = activating.Context.Resolve<IFactory>();
        var closedProductBuilder = openProductBuilder.MakeGenericMethod(productModel);
        object productObject = closedProductBuilder.Invoke(this, new object[] { factory, productIdentifier });
        handler.ReplaceInstance(productObject);
    })
    .AsImplementedInterfaces();

我们有一种辅助方法,因此我们仅依赖于此Mongo Module类中反映方法

private IProduct<TModel> CreateProduct<TModel>(IFactory factory, string identifier)
{
    return factory.CreateProduct<TModel>(identifier);
}

现在,显然这比第一种方法更好,并且不依赖太多的反射。不幸的是,每当我们想要真实的对象时,它确实涉及创建一个虚拟对象。很烂!

问题:使用AUTOFAC有另一种方法吗?我可以以某种方式创建AutoFac可以使用的通用工厂方法吗?我的主要目标是切出创建虚拟类型,然后直接跳过调用CreateProduct代码。

NOTES :我已经删除了一个相当多的错误检查等。通常我会做的,以使这个问题尽可能短,而仍然充分证明了问题和我当前的解决方案。

如果工厂中没有非通用Create方法,您将需要呼叫MakeGenericMethod

而不是OnActivating事件,您可以使用IRegistrationSource组件,该组件将与您的解决方法相同2

internal class FactoryRegistrationSource : IRegistrationSource
{
    private static MethodInfo openProductBuilder = typeof(Factory).GetMethod(nameof(Factory.CreateProduct));
    public Boolean IsAdapterForIndividualComponents => false;
    public IEnumerable<IComponentRegistration> RegistrationsFor(Service service, Func<Service, IEnumerable<IComponentRegistration>> registrationAccessor)
    {
        IServiceWithType typedService = service as IServiceWithType;
        if (typedService != null && typedService.ServiceType.IsClosedTypeOf(typeof(IProduct<>)))
        {
            IComponentRegistration registration = RegistrationBuilder.ForDelegate(typedService.ServiceType, (c, p) =>
             {
                 IFactory factory = c.Resolve<IFactory>();
                 Type productModel = typedService.ServiceType.GetGenericArguments().First();
                 String productIdentifier = productModel.GetCustomAttribute<ProductIdentifierAttribute>()?.Identifier;
                 MethodInfo closedProductBuilder = openProductBuilder.MakeGenericMethod(productModel);
                 Object productObject = closedProductBuilder.Invoke(factory, new object[] { productIdentifier });
                 return productObject;
             }).As(service).CreateRegistration();
            yield return registration;
        }
        yield break;
    }
}

最新更新