我正在努力通过我的 WebApi 2 项目中的 autofac 连接依赖项。我有一个以下接口和类,我想在我的 GET 和 POST 控制器操作中注入它们,
public interface IRepository
{
IContext Context
{
get;
}
void SomeOperation();
}
public MyRepository : IRepository
{
IContext _context;
public MyRepository(IContext context)
{
_context = context;
}
public Context
{
get
{
return _context;
}
}
public void SomeOperation
{
// Perform some operation using _context;
}
}
我希望 IRepository 像这样注入控制器,
public class MyController : ApiController
{
private readonly IRepository _repo;
public ApplicationsController(IRepository repo)
{
_repo = repo;
}
// GET: api/v1/Contexts({contextId})
public IHttpActionResult Get(string contextId)
{
_repo.SomeOperation();
}
}
要在 MyRepository 中注入的 IContext 对象必须从工厂中获取,就像这样
public class ContextFactory
{
Hashtable contextMap;
IContext Get(string contextId)
{
if contextMap.Contains(contextId)
return contextMap[contextId].Value;
else
{
IContextConfiguration configuration = ContextConfigurationFactory.Get(contextId);
IContext context = new ConcreteContext(configuration);
contextMap.Add[contextId, context];
return context;
}
}
}
我不确定如何通过 Autofac 注入关系来连接所有类并转换工厂类中的逻辑,以便在 url 中传递的上下文 id 传递给 ContextConfigurationFactory.Get 并在哈希中找不到时实例化 ConcreteContext 对象,最终 Autofac 注入正确的上下文对象在 MyRepository 中,然后将其传递给控制器中的 Get 操作。