如何将受控生命周期关系类型(即 Owned<T>)与委托工厂相结合?

How do I combine a Controlled Lifetime relationship type (i.e. Owned<T>) with a delegate factory?

在我的应用程序中,我有一项服务需要 Autofac 未解析的构造函数参数,我使用委托工厂对其进行了实例化:

public class Service
{
    public Service(string parameter /*, ... other dependencies */)
    {
    }

    public delegate Service Factory(string parameter);
}

效果很好!我真的很喜欢这个功能。

我也喜欢 Controlled Lifetime 关系,所以我可以让我的组件依赖于 Func<Owned<ISomething>> 像这样:

public class Component
{
    private Func<Owned<ISomething>> _somethingFactory;

    /* constructor omitted for brevity */

    public void DoSomethingUseful()
    {
       using (var ownedSomething = _somethingFactory())
       {
           /* Lots of useful code here */
       }
    }
}

我的问题是现在我想将两者结合起来。我不能注入 Func<Owned<Service>> 的实例,因为它需要那个参数,所以我目前的解决方案是将工厂抽象到另一个服务中,比如 IServiceFactory:

public interface IServiceFactory
{
    Service Create(string parameter);
}

...这样实现:

public class ServiceFactory : IServiceFactory
{
    private Service.Factory _internalFactory;

    public ServiceFactory(Service.Factory internalFactory)
    {
        _internalFactory = internalFactory;
    }

    public Service Create(string parameter)
    {
        return _internalFactory(parameter);
    }
}

然后我的组件变成这样:

public class Component
{
    Func<Owned<IServiceFactory>> _serviceFactoryFactory;

    /* ... */ 
}

需要这样一个字段名让我觉得不好,以至于我怀疑必须有一种更简洁的方法来处理这种情况。

还有其他方法吗?

您可以更改注入的工厂以包含字符串参数:

private Func<string, Owned<ISomething>> _somethingFactory;

然后你可以在你想创建一个新实例时将string传递给工厂:

public void DoSomethingUseful()
{
   using (var ownedSomething = _somethingFactory("my parameter"))
   {
       /* Lots of useful code here */
   }
}

我创建了一个 .NET Fiddle 和一个小的工作样本。