【发布时间】:2018-02-12 09:43:30
【问题描述】:
我一直在我的集成测试中手动实例化我的服务,但是当我得到一个具有 Lazy 依赖项的服务时,我做了一些研究并发现 you can actually use Autofac to resolve your services when doing your tests。
所以,我写了这个类:
public class Container<TModule> where TModule: IModule, new()
{
private readonly IContainer _container;
protected Container()
{
var builder = new ContainerBuilder();
builder.RegisterModule(new TModule());
_container = builder.Build();
}
protected TEntity Resolve<TEntity>() => _container.Resolve<TEntity>();
protected void Dispose() => _container.Dispose();
}
然后在我的上下文中,我改为:
public class ProductContext : Container<AutofacModule>
{
public IProductProvider ProductProvider { get; }
public static ProductContext GiventServices() => new ProductContext();
protected ProductContext()
{
ProductProvider = Resolve<IProductProvider>();
}
public List<JObject> WhenListProducts(int categoryId) => ProductProvider.List(categoryId);
}
我有另一个似乎可以工作的上下文(测试通过),它正在使用 MatchProvider。如果我在我的 Autofac 模块中比较两者,它们看起来像这样:
builder.RegisterType<ProductProvider>().As<IProductProvider>().InstancePerRequest();
和
builder.RegisterType<MatchProvider>().As<IMatchProvider>().SingleInstance();
因为 MatchProvider 是一个单例,它似乎没有解决任何问题,但 ProductProvider 是每个请求的实例,这似乎是问题所在.
在运行任何需要该服务的测试时出现此错误:
从请求实例的范围中看不到带有匹配“AutofacWebRequest”标签的范围。
我认为这是因为我没有安装正确的 nuget 包。所以我安装了:
- Autofac
- Autofac.Integration.Owin
- Autofac.Integration.WebApi
- Autofac.Integration.WebApi.Owin
这些是在定义我的模块时使用的相同引用,但这没有帮助。 有谁知道我需要做什么才能让它工作?
【问题讨论】:
标签: c# testing asp.net-web-api integration-testing autofac