与其他现代 DI 容器(例如 Autofac 和 Simple Injector)一样,一旦应用程序启动,就不可能更改容器的配置。例如,在不同 DI 容器的文档的本节中解释了在应用程序运行时能够更改配置的问题和风险。
然而,这些限制确实迫使您采取不同的方法。可能有多种解决方案,但大多数解决方案在概念上都归结为同一件事,即:不要替换组件,而是更新该组件的状态。
这是一个例子:
凭据的数据容器:
// This data structure is immutable.
public sealed class InstaCredentials
{
public string UserName { get; }
public string Password { get; }
public InstaCredentials(string userName, string password)
{
this.UserName = userName;
this.Password = password;
}
}
Insta 服务的抽象:
public interface IInstaService
{
// Method to apply credentials coming from the user
void SetCredentials(InstaCredentials credentials);
}
使用 IInstaService 的控制器:
public sealed class HomeController
{
private readonly IInstaService instaService;
public HomeController(IInstaService instaService)
{
this.instaService = instaService;
}
public void LogIn(LogInModel model)
{
// Apply credentials
var credentials = new InstaCredentials(model.UserName, model.Password);
this.instaService.SetCredentials(credentials);
}
}
Insta服务实现:
public sealed class InstaServiceIMpl : IInstaService
{
private InstaCredentials credentials = new InstaCredentials(null, null);
public void SetCredentials(InstaCredentials credentials)
{
this.credentials = credentials ?? throw new ArgumentNullException(nameof(credentials));
}
}