从控制台应用程序中的主要方法进行DI

c#

我有一堂课

public class A
{
    public A(IB b)
    {
    }

    public void Method1()
    {
    }
}

class Program
{
     static void Main(string[] args)
     {
         var serviceProvider = new ServiceCollection()
            .AddSingleton<IB,B>()
            .BuildServiceProvider();
        //How to call Method1 of classA
        classA a = new classA(); 
     }
}

如何Method1()Main方法调用?

我收到一个编译时错误,因为“不存在重载方法”。

回答

应用程序中的 DI 需要在某处进行引导。例如,在 ASP.NET 中,这发生在框架内部,“看不见”。

在这里,您必须注册并解析 A 类:

 static void Main(string[] args)
 {
     var serviceProvider = new ServiceCollection()
        .AddSingleton<IB,B>()
        .AddTransient<A>()     // Transient or Singleton, it depends
        .BuildServiceProvider();

    //How to call Method1 of classA
    // classA a = new classA(); 

    var a  = serviceProvider.GetRequiredService<A>();
 }


以上是从控制台应用程序中的主要方法进行DI的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>