对 Controller 类以外的类进行依赖注入 [英] Dependency Injection with classes other than a Controller class
问题描述
此时我正在轻松地将东西注入我的控制器,在某些情况下构建我自己的 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 thinking whether I can do the same for for my own classes. 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
.
推荐答案
以下是使用 DI 的工作示例,不涉及 MVC 控制器.这是我需要做的来理解这个过程,所以也许它会帮助其他人.
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("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();
}
}
}
这篇关于对 Controller 类以外的类进行依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!