簡體   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