除Controller类之外的其他类的依赖注入

除Controller类之外的其他类的依赖注入

本文介绍了除Controller类之外的其他类的依赖注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这时,我可以轻松地将内容注入Controller中,在某些情况下,可以构建自己的ResolverServices类。 生活是美好的

At this point I'm injecting things into my Controllers with ease, in some cases building my own ResolverServices class. Life is good.

我不知道该怎么做,就是获得一个自动注入非控制器类的框架。起作用的是使框架自动注入我的控制器 IOptions 中,这实际上是我项目的配置:

What I cannot figure out how to do is get the framework to automatically inject into non-controller classes. What does work is having the framework automatically inject into my controller IOptions, which is effectively the configuration for my project:

public class MessageCenterController : Controller
{
    private readonly MyOptions _options;

    public MessageCenterController(IOptions<MyOptions> options)
    {
        _options = options.Value;
    }
}

我认为我可能会遇到同样的情况我自己的类,我假设我在模仿控制器时就关闭了,就像这样:

I'm think I can have the same happen for my own classes an I assume I'm close when I mimic the controller, like this:

public class MyHelper
{
    private readonly ProfileOptions _options;

    public MyHelper(IOptions<ProfileOptions> options)
    {
        _options = options.Value;
    }

    public bool CheckIt()
    {
        return _options.SomeBoolValue;
    }
}

我认为我失败的地方是当我打电话时像这样:

I think where I'm failing is when I call it like this:

public void DoSomething()
{
    var helper = new MyHelper(??????);

    if (helper.CheckIt())
    {
        // Do Something
    }
}

我一直追踪到的问题实际上是在控制器级别上谈论DI的所有内容。我尝试在 Controller 对象源代码中查找它发生的位置,但是在其中有点发疯了。

The problem I have tracking this down is practically everything that talks about DI is talking about it at the controller level. I tried hunting down where it happens in the Controller object source code, but it gets kinda crazy in there.

我知道我可以手动创建IOptions实例并将其传递给 MyHelper 构造函数,但是似乎我应该能够使框架做到这一点,因为它适用于控制器

I do know I can manually create an instance of IOptions and pass it to the MyHelper constructor, but it seems like I should be able to get the framework do that since it works for Controllers.

感谢您的帮助。

推荐答案

下面是一个不使用MVC控制器而直接使用DI的有效示例。这是我需要做的,以了解该过程,所以也许会对其他人有所帮助。

Below is a working example of using DI without anything that involves MVC Controllers. This is what I needed to do to understand the process, so maybe it will help somebody else.

ShoppingCart对象通过DI获得INotifier实例(该实例通知

The ShoppingCart object gets, via DI, an instance of INotifier (which notifies the customer of their order.)

using Microsoft.Extensions.DependencyInjection;
using System;

namespace DiSample
{
    // STEP 1: Define an interface.
    /// <summary>
    /// Defines how a user is notified.
    /// </summary>
    public interface INotifier
    {
        void Send(string from, string to, string subject, string body);
    }

    // STEP 2: Implement the interface
    /// <summary>
    /// Implementation of INotifier that notifies users by email.
    /// </summary>
    public class EmailNotifier : INotifier
    {
        public void Send(string from, string to, string subject, string body)
        {
            // TODO: Connect to something that will send an email.
        }
    }

    // STEP 3: Create a class that requires an implementation of the interface.
    public class ShoppingCart
    {
        INotifier _notifier;

        public ShoppingCart(INotifier notifier)
        {
            _notifier = notifier;
        }

        public void PlaceOrder(string customerEmail, string orderInfo)
        {
            _notifier.Send("[email protected]", customerEmail, $"Order Placed", $"Thank you for your order of {orderInfo}");
        }

    }

    public class Program
    {
        // STEP 4: Create console app to setup DI
        static void Main(string[] args)
        {
            // create service collection
            var serviceCollection = new ServiceCollection();

            // ConfigureServices(serviceCollection)
            serviceCollection.AddTransient<INotifier, EmailNotifier>();

            // create service provider
            var serviceProvider = serviceCollection.BuildServiceProvider();

            // This is where DI magic happens:
            var myCart = ActivatorUtilities.CreateInstance<ShoppingCart>(serviceProvider);

            myCart.PlaceOrder("[email protected]", "2 Widgets");

            System.Console.Write("Press any key to end.");
            System.Console.ReadLine();
        }
    }
}

这篇关于除Controller类之外的其他类的依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 01:31