在这一点上,我正在轻松地将东西注入(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/