.net core 非控制器类的依赖注入和调用

.net core 非控制器类的依赖注入和调用,.net-core,dependencies,.net Core,Dependencies,我试图将注意力集中在依赖注入上,它来自静态类和实例化类的世界。以下是我目前拥有的: [SomeFilter] public class AController : Controller { private readonly IOptions<AppSettings> _appSettings; public AController(IOptions<AppSettings> appSettings) { _appSettings = appSet

我试图将注意力集中在依赖注入上,它来自静态类和实例化类的世界。以下是我目前拥有的:

[SomeFilter]
public class AController : Controller
{
    private readonly IOptions<AppSettings> _appSettings;

    public AController(IOptions<AppSettings> appSettings)
{
    _appSettings = appSettings;
}

// GET: /characters/
public IActionResult Index()
{
    //do something
}
OtherClass如下所示:

public class OtherClass
{
    private readonly IOptions<AppSettings> _appSettings;

    public OtherClass(IOptions<AppSettings> appSettings)
{
    _appSettings = appSettings;
}

public RunMe()
{
    //do something
}
公共类其他类
{
私有只读IOPS\u应用设置;
公共OtherClass(IOOptions appSettings)
{
_appSettings=appSettings;
}
公共运行名()
{
//做点什么
}
我还在Startup.cs中将OtherClass注册为service.Singleton

我得到一个错误声明:

“非静态字段需要对象引用”

对于
OtherClass.RunMe();
调用


我假设我可以从代码中的任何地方调用这个类,而不必创建它的新实例?本质上,我如何使用依赖项注入从其他类调用方法?

你不能在过滤器上进行构造函数注入。这都是关于运行时顺序的。当你尝试在构造函数上注入时,你的IoC co目前无法访问ntainer。应使用属性/设置器注入

我更喜欢使用structuremap容器来实现这一点。因为structuremap非常容易应用任何类型注入。例如,当您有这样的筛选器注册表时

 public class ActionFilterRegistry : Registry
    {
        public ActionFilterRegistry(Func<IContainer> containerFactory)
        {
            For<IFilterProvider>().Use(
                new StructureMapFilterProvider(containerFactory));

            Policies.SetAllProperties(x =>
                x.Matching(p =>
                    p.DeclaringType.CanBeCastTo(typeof(ActionFilterAttribute)) &&
                    p.DeclaringType.Namespace.StartsWith("YourNameSpace") &&
                    !p.PropertyType.IsPrimitive &&
                    p.PropertyType != typeof(string)));
        }
    }

然后,您可以使用任何带注入的过滤器。但请注意,您不应该像使用构造函数注入一样使用构造函数注入。

我找到了一种使用

[ServiceFilter(typeof(MyFilter))] 
而不仅仅是

[MyFilter] 
在过滤器的内部

(ActionExecutingContext context)
{
    var controller = context.Controller as Controller.  
    controller.whateverIneed
}
现在,这为我提供了过滤器中所需的内容。我还意识到,我无法消除使用
new
创建对其他类的引用的需要,因为我觉得Core的依赖性完全是关于“不再
new
”。这涉及到我仍然掌握的Core的基础知识

我最后做的是创建新的类来做一些工作,但它们被设置为服务并在startup.cs中注册。我仍然在努力解决如何混合注册的服务(我可以注入)和工作类的新实例(通常包含静态信息),以及如何在它们之间传递信息

[MyFilter] 
(ActionExecutingContext context)
{
    var controller = context.Controller as Controller.  
    controller.whateverIneed
}