AutoFac - 如何使用参数注册和解析对象?

AutoFac - How to register and resolve an object with parameter?

public class FooController : ApiController
{
   private IDb db;
    public FooController (IDb context)
    {
        db = context;
    }

    public void DoSomething(string value)
    {
        var output = new DoSomethingElse(value);
    }
}

DoSomethingElse 对象被此 class 中的几个方法使用,但这并不是所有方法的要求。如何注册和解决DoSomethingElse?

我理解的问题:

public class FooController : ApiController
{
   private IDb db;
    public FooController (IDb context)
    {
        db = context;
    }

    public void DoSomething(string value)
    {
        var output = new DoSomethingElse(value);
    }
}

您不想在每次实例化 FooController 时都实例化 DoSomethingElse 类型。您还想在 运行 时间为其提供一个值。

所以这需要工厂模式:

public interface IDoSomethingElseFactory
{
    IDoSomethingElse Create(string value);
}

public class DoSomethingElseFactory : IDoSomethingElseFactory
{
    public IDoSomethingElse Create(string value)
    {
        // Every call to this method will create a new instance
        return new DoSomethingElse(value);
    }
}

public class FooController : ApiController
{
    private IDb db;
    private readonly IDoSomethingElseFactory doSomethingElseFactory;

    public FooController (
        IDb context,
        IDoSomethingElseFactory doSomethingElseFactory)
    {
        db = context;
        this.doSomethingElseFactory = doSomethingElseFactory;
    }

    public void DoSomething(string value)
    {
        // this will be the point at which a brand new
        // instance of `DoSomethingElse` will be created.
        var output = doSomethingElseFactory.Create(value);
    }
}

然后注册:

builder.RegisterType<DoSomethingElseFactory>()
       .As<IDoSomethingElseFactory>()