使用 Simple Injector 在控制台应用程序中设置解析器

SetResolver in console application using Simple Injector

我想做类似的事情:

DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));

但是在控制台应用程序中。我也有需要以工作者角色执行此操作的情况。我不想到处添加对 MVC dll 的引用。我想知道是否有非 mvc 项目的等效项?我需要存储我创建的容器,以便我可以在我的整个应用程序中访问它。我想创建一个静态变量,但我不想这样做。

我看到有一个用于简单注入器的 CommonSerivceLocator nuget,但奇怪的是它需要 2.8.1,而最新的非 mvc 简单注入器是 2.8.0。

I don't want to have to add a reference to the MVC dll all over the place.

This indicates that you are not applying dependency injection but are doing Service Location, which is an anti-pattern.

If you apply constructor injection to all your components, you will be able to let Simple Injector build up a complete object graph of dependent components (of many levels deep) without any of your components to know about the existence of an IoC container such as Simple Injector or an IoC abstraction such as the Common Service Locator and MVC's IDependencyResolver. This prevents you from referencing your IoC container or such abstraction "all over the place".

So in a Console Application that means that you typically have one place where you resolve the object graph(s). This is the place in the application that already knows about the existence of the IoC container. This place is typically referred to as the Composition Root.

I saw there is a CommonSerivceLocator nuget for Simple Injector but oddly it requires 2.8.1 and the latest non-mvc Simple Injector is 2.8.0.

I seem to have made an error in the build scripts that create the NuGet packages and although NuGet usually applies checks when a package is uploaded, for some reason it failed to check this. I fixed this and pushed v2.8.2 of the CommonServiceLocator adapter to NuGet. But note that we are dropping support for the CSL adapter in v3 of Simple Injector because it leads to bad practice. Don't use it; you don't need it.