This answer顯示瞭如何使用不帶參數的工廠接口來解析實例。如何在具有參數的簡單噴油器中實現工廠接口
我使用下面的代碼
public interface ISimpleBarFactory
{
Bar CreateBar(int value);
}
public sealed class SimpleBarFactory : ISimpleBarFactory
{
private readonly Container _container;
public SimpleBarFactory (Container container)
{
_container = container;
}
public Bar CreateBar(int value)
{
_container.Register(() => new Bar(vlue));
return _container.GetInstance<Bar>();
}
}
解決具有構造函數的參數情況。
The container can't be changed after the first call to GetInstance, GetAllInstances and Verify.
這是解決使用工廠接口與參數情況下,正確的做法:
然而,使用工廠來實例化服務類,當我得到下面的異常?
更新
以下是我的代碼。我正在從Ninject遷移代碼。
public interface IFormsUIFactory
{
AccountUI CreateAccountUI(Account account);
}
public class FormsUIFactory
{
private readonly IFormsUIFactory _uiFactory;
public FormsUIFactory(IFormsUIFactory uiFactory)
{
_uiFactory = uiFactory;
}
public void CreateAccountUI(Account account)
{
_uiFactory.CreateAccountUI(account);
}
}
UI類將被注入
public partial class AccountUI : Form
{
private readonly IAccountMaintenanceProcessor _processor;
private readonly Account _account;
public AccountUI(IAccountMaintenanceProcessor accountProcessor, Account account)
{
_processor = accountProcessor;
_account = account;
}
}
實例化代碼:
var account = new Account();
// Populate values for the account
var frm = _uiFactory.CreateAccountUI(account);
您使用的是什麼IoC? –
關鍵是你應該在應用程序啓動時只註冊'Bar' ** **一次**。並使用像動態參數解析來傳遞'value'。您需要知道您使用的是哪種IoC,因爲每個IoC都有不同的方式(語法) –
我正在使用簡單噴油器 – kagundajm