卡利本。微型的
SimpleContainer
实现不支持在解析期间提供额外参数的构造函数注入。还有其他支持该场景的依赖项注入容器,但您可以通过使用工厂模式轻松绕过此限制。
下面的示例演示了
CustomerViewModel
CustomerDatabase
实例:
/// <summary>
/// This is just some dependency that you want to use in your view models.
/// </summary>
interface ICustomerDatabase
{
void DeleteByName(string name);
}
class CustomerDatabase : ICustomerDatabase
{
public void DeleteByName(string text)
{
Console.WriteLine($"Customer '{text}' has been deleted.");
}
}
/// <summary>
/// This customer view model has a dependency on an
/// <see cref="ICustomerDatabase"/>-Implementation, but also
/// needs the customer name during construction for some reason.
/// </summary>
class CustomerViewModel
{
public CustomerViewModel(string customerName, ICustomerDatabase database)
{
this.Name = customerName;
this.Database = database;
}
public string Name { get; }
public ICustomerDatabase Database { get; }
public void Delete()
{
this.Database.DeleteByName(this.Name);
}
}
/// <summary>
/// To support parameters, we use the factory pattern: The factory
/// gets the view model's dependencies as its own dependencies
/// by using constructor injection. The <see cref="Create"/>-Method
/// then supplies any additional parameters. You can also use
/// multiple factory methods that correspond with different
/// constructor overloads.
/// </summary>
class CustomerViewModelFactory
{
public CustomerViewModelFactory(ICustomerDatabase service)
{
this.Service = service;
}
public ICustomerDatabase Service { get; }
public CustomerViewModel Create(string text)
{
return new CustomerViewModel(text, this.Service);
}
}
class Program
{
private static void Main()
{
var c = new SimpleContainer();
// First, we register the factory and the service.
c.RegisterSingleton(typeof(CustomerViewModelFactory), null, typeof(CustomerViewModelFactory));
c.RegisterSingleton(typeof(ICustomerDatabase), null, typeof(CustomerDatabase));
// Later on, we depend on the factory, not the view model itself.
// We would use the factory as constructor parameter
// everywhere we need to create view model instances.
var factory = c.GetInstance<CustomerViewModelFactory>();
// We create a view model instance using the factory.
var viewModel = factory.Create("TestCustomer");
viewModel.Delete();
Console.ReadKey();
}
}