c# - 使用 Controller 类以外的类进行依赖注入(inject)

标签 c# asp.net-core .net-core dependency-injection asp.net-core-mvc

在这一点上,我正在轻松地将东西注入(inject)我的 Controller ,在某些情况下构建我自己的 ResolverServices 类。 生活是美好的

我不知道该怎么做是让框架自动注入(inject)到非 Controller 类中。真正起作用的是让框架自动注入(inject)我的 Controller IOptions,这实际上是我项目的配置:

public class MessageCenterController : Controller
{
    private readonly MyOptions _options;

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

我在考虑我是否可以为我自己的类(class)做同样的事情。当我模仿 Controller 时,我假设我很接近,就像这样:

public class MyHelper
{
    private readonly ProfileOptions _options;

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

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

我认为我失败的地方是当我这样调用它时:

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

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

我追踪到的问题实际上是所有谈论 DI 的事情都是在 Controller 级别谈论它。我试着找出它在 Controller 对象源代码中发生的位置,但它在那里变得有点疯狂。

我确实知道我可以手动创建 IOptions 的实例并将其传递给 MyHelper 构造函数,但似乎我应该能够让框架执行此操作,因为它适用于 Controller

最佳答案

下面是一个在不涉及 MVC Controller 的情况下使用 DI 的工作示例。这是我需要做的来理解这个过程,所以也许它会对其他人有所帮助。

ShoppingCart 对象通过 DI 获取 INotifier 的实例(通知客户他们的订单。)

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("admin@store.com", 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("customer@home.com", "2 Widgets");

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

关于c# - 使用 Controller 类以外的类进行依赖注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37189984/

相关文章:

sql-server - 从 Azure Function App 连接到 SQL DB 时出现 SqlException 服务器未找到错误

c# - jQuery getScript 失败

c# - 从使用委托(delegate)搜索不同属性的对象中返回属性?

asp.net-core - 我如何知道 Linux 中是否安装了 ASP.NET Core?

asp.net-core - 在 ASP.NET Core 3.1 中设置值比较器

c# - 未授予所需的权限。必须至少授予其中一项权限 : Users

c# - 如何使用 polly 在 .Net core 中进行动态抖动退避等待和重试

c# - 在 C# 中为 MS Access 创建事务

c# - 使用 TFS API,我如何找到在代码审查中所做的评论?

c# - 为什么我的通用服务会收到错误 "Cannot instantiate implementation type"?