public class FooController : ApiController
{
private IDb db;
public FooController (IDb context)
{
db = context;
}
public void DoSomething(string value)
{
var output = new DoSomethingElse(value);
}
}这个类中有几个方法使用了DoSomethingElse对象,但并不是所有方法都需要这个对象。如何注册和解析DoSomethingElse
发布于 2016-07-21 17:32:00
我所理解的问题是:
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>()https://stackoverflow.com/questions/38499628
复制相似问题