![](/img/trans.png)
[英]Autofac - The requested service (lSomeDbContext) has not been registered
[英]The requested service has not been registered ! AutoFac Dependency Injection
我只是尝试使用AutoFac来解决依赖关系,但它会抛出异常,例如
请求的服务“ProductService”尚未注册。 要避免此异常,请注册组件以提供服务或使用IsRegistered()...
class Program
{
static void Main(string[] args)
{
var builder = new ContainerBuilder();
builder.RegisterType<ProductService>().As<IProductService>();
using (var container = builder.Build())
{
container.Resolve<ProductService>().DoSomething();
}
}
}
public class ProductService : IProductService
{
public void DoSomething()
{
Console.WriteLine("I do lots of things!!!");
}
}
public interface IProductService
{
void DoSomething();
}
我做错了什么?
声明:
builder.RegisterType<ProductService>().As<IProductService>();
告诉Autofac每当有人试图解析IProductService
给他们一个ProductService
因此,您需要解析IProductService
和ProductService
:
using (var container = builder.Build())
{
container.Resolve<IProductService>().DoSomething();
}
或者如果你想让Resolve<ProductService>
在AsSelf中注册它:
builder.RegisterType<ProductService>().AsSelf();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.