简体   繁体   中英

How to pass a parameter indirectly in Autofac

I have a dependency being injected via Func<Owned<OwnedDependency>> . One of its dependencies requires a parameter that I will only have at the point of constructing OwnedDependency.

public class OwnedDependency
{
    public OwnedDependency(IDependency1 dependency)
    {
    }
}

public interface IDependency1
{
}

public class Dependency1 : IDependency1
{
    public Dependency1(MyParameter parameter)
    {
    }
}

public class MyClass
{
    private readonly Func<Owned<OwnedDependency>> m_ownedDependencyFactory;

    public MyClass(Func<Owned<OwnedDependency>> ownedDependencyFactory)
    {
        m_ownedDependencyFactory = ownedDependencyFactory;
    }

    public void CreateOwnedDependency()
    {
        var parameter = new MyParameter(...);
        // ** how to setup parameter with the container? **

        using (var ownedDependency = m_ownedDependencyFactory())
        {
        }
    }
}

I can't work out a clean way of setting up the instance of MyParameter.

One approach I have explored is to inject ILifetimeScope into MyClass and then do something like:

var parameter = new MyParameter(...);

using (var newScope = m_lifetimeScope.BeginLifetimeScope())
{
    newScope.Resolve<IDependency1>(new TypedParameter(typeof(MyParameter), parameter));
    var ownedDependency = newScope.Resolve<OwnedDependency>();
    // ...
}

but the container is becoming unnecessarily intrusive. Ideally what I would like to do is inject Func<IDependency1, Owned<OwnedDependency>> and the container be willing to use parameters passed in to satisfy any necessary dependency, not just the ones on OwnedDependency.

What about doing the resolution in two steps with using another factory for IDependency1 :

public class MyClass
{
    private Func<MyParameter, IDependency1> dependency1Factory;
    private Func<IDependency1, Owned<OwnedDependency>> ownedDependencyFactory;


    public MyClass(
        Func<MyParameter, IDependency1> dependency1Factory,
        Func<IDependency1, Owned<OwnedDependency>> ownedDependencyFactory)
    {
        this.dependency1Factory = dependency1Factory;
        this.ownedDependencyFactory = ownedDependencyFactory;
    }

    public void CreateOwnedDependency()
    {
        var parameter = new MyParameter();
        using (var owned = ownedDependencyFactory(dependency1Factory(parameter)))
        {
        }

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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