asp.net-core - 每次需要实例时如何设置控制台应用程序不使用 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 中的自动注入的信息。这是显而易见的事情,我无法弄清楚吗?
解决方案
我认为这对您很有用 如果您对设计模式有所了解,我认为您可以使用外观设计模式
所以有关更多信息,我建议阅读
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**
}
}
我希望这对你有用。
推荐阅读
- java - 为什么循环运行时 MouseListener 不起作用?
- android - 使用匕首时的警告:“@Component.Builder 具有不需要的模块或组件的设置器”
- python - Kivy关于希腊字符的Android字符串连接问题
- selenium - 在 Linux 中运行简单程序时出现 Selenium 错误
- javascript - 使用 Three.js 加载 600 万个三角形会使浏览器崩溃
- python - 如何避免在源代码中保留版本号?
- html - 如何在下拉菜单中调整或格式化块中的文本
- node.js - 在 Azure Pipelines 中运行 npm 版本脚本
- python - 通过 datetime.date 列表选择数据帧行(datetimeindex)
- javascript - 如何使用 img (即 href 链接)和单选按钮(值或 id)制作一个功能并转到下一页