首页 > 解决方案 > 每次需要实例时如何设置控制台应用程序不使用 GetService

问题描述

我试图了解 DI 进程如何在 .net 核心中工作,基本上每个基本示例都类似于:

class Program
    {
        static void Main(string[] args)
        {
            var collection = new ServiceCollection();
            collection.AddScoped<IBusiness, Business>();
            var provider = collection.BuildServiceProvider();
            //getting an instance is through GetService<>()
            IBusiness biz = provider.GetService<IBusiness>();
        }
    }

    public class Business : IBusiness
    {
        public void DoSomeBusiness()
        {
            Console.Write("This is very serious business stuff");
        }
    }

    public interface IBusiness
    {
        void DoSomeBusiness();
    }

这很简单——想要实例化一些服务,使用 povider.GetService()。

另一方面,在 asp.net 应用程序中,您不需要显式调用 GetService,应用程序只是在您引用它的接口时注入所需的对象,如下所示:

public class HomeController : Controller
    {
        private readonly IBoardGameRepository _boardGameRepository;


        public HomeController(IBoardGameRepository boardGameRepository)
        {
            _boardGameRepository = boardGameRepository;
        }


        public IActionResult Index()
        {
            var boardGames = _boardGameRepository.GetAllBoardGames();
            //do some logic and return boardagames into view
        }
    }

我从来没有找到有关如何从在我的控制台应用程序中调用 GetService 到使用像 asp.net 中的自动注入的信息。这是显而易见的事情,我无法弄清楚吗?

标签: asp.net-coredependency-injectionconsole-application

解决方案


我认为这对您很有用 如果您对设计模式有所了解,我认为您可以使用外观设计模式

所以有关更多信息,我建议阅读
C# 中的外观设计模式

但我想说它对你有什么用。

你应该创建另一个类......只需遵循代码

    Public class FacadeClass 
    { 
       private readonly IBusiness _business;
       
       public FacadeClass () 
       { 
         _business = new Business();
       }

       ***Write your methode here***

    }
  

然后在你的项目中使用它。以下代码...

class Program
    {
        static void Main(string[] args)
        {
            var facadeForClient = new FacadeClass ();
            
            facadeForClient.**Your Methode Name**

        }
    }

我希望这对你有用。


推荐阅读