在 Web API (1) 中使用构造函数参数加载存储库



我正在尝试使用autofac获得以下场景,但我不确定如何构建我的代码来启动和运行它。

我有一个存储库类,这个存储库类需要在初始化(构造函数)时获取项目键(字符串)。我想在初始化由 Web API 提供给我的"初始化"方法时实例化此存储库,因为项目密钥将在我的路由中可用。

所以与其调用"new ProductRepository(projectKey)",我想使用Autofac。有人可以指出我正确的方向吗?我没有找到任何方法将特定数据发送到 web api 中的容器,因为容器/构建器仅在 appStart 中可用。我应该将容器作为单一实例提供,以便我可以接近它,还是这种做法很糟糕?

在初始化代码中:

var builder = new ContainerBuilder();
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
var container = builder.Build();
var resolver = new AutofacWebApiDependencyResolver(container);
config.DependencyResolver = resolver;

在控制器中:

public class MyController : ApiController
{
    public MyController(IComponentContext container)
    { 
        var key = new NamedParameter("projectKey", "keyFromRoute");
        var repository = container.Resolve<ProductRepository>(key);
    }
}

这应该可以做到。

有一个 nuget 包,它为 WebApi 提供了一个与 AutoFac 集成的DependencyResolver。 创建依赖项解析程序,将其分配给配置,在 autofac 容器中注册控制器。

我做了一些假设,因为你没有提供你的代码,但我认为你有这样的东西:

public class ProductRepository
{
    public ProductRepository(DbContext dbContext, int projectKey)
    {
    }
}
public class SomeController : Controller
{
    private readonly Func<int, ProductRepository> _repoFactory;
    public SomeController(Func<int, ProductRepository> repoFactory)
    {
        _repoFactory = repoFactory;
    }
    public void DoStuff(int projectKey)
    {
        var repo = _repoFactory(projectKey);
        repo.DoStuff();
    }
}

public class RepositoryModule : Module
{
    public override Load(ContainerBuilder builder)
    {
        builder.RegisterType<ProductRepository>();
    }
}

最新更新