繁体   English   中英

请求的服务尚未注册! AutoFac依赖注入

[英]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

因此,您需要解析IProductServiceProductService

using (var container = builder.Build())
{
    container.Resolve<IProductService>().DoSomething();
}

或者如果你想让Resolve<ProductService>在AsSelf中注册它:

builder.RegisterType<ProductService>().AsSelf();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM