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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15449118/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 16:52:12  来源:igfitidea点击:

The requested service has not been registered ! AutoFac Dependency Injection

c#.netdependency-injectionautofac

提问by Bar?? Velio?lu

I am simply trying to use AutoFac to resolve dependencies but it throws exception such as

我只是想使用 AutoFac 来解决依赖关系,但它会抛出异常,例如

The requested service 'ProductService' has not been registered. To avoid this exception, either register a component to provide service or use IsRegistered()...

请求的服务“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();
}

What I have done wrong ?

我做错了什么?

采纳答案by nemesv

With the statement:

声明如下:

builder.RegisterType<ProductService>().As<IProductService>();

Told Autofac whenever somebody tries to resolve an IProductServicegive them an ProductService

告诉Autofac每当有人试图解决一个IProductService给他们ProductService

So you need to resolve the IProductServiceand to the ProductService:

所以你需要解决IProductService和 到ProductService

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

Or if you want to keep the Resolve<ProductService>register it with AsSelf:

或者,如果您想将其Resolve<ProductService>注册到 AsSelf:

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