2 回答

TA貢獻(xiàn)1831條經(jīng)驗(yàn) 獲得超4個(gè)贊
我想解決這個(gè)問題最干凈的方法是創(chuàng)建一個(gè)工廠:
interface IForm1Factory
{
Form1 Create(int valueToEdit);
}
class Form1Factory
{
public readonly ILogger _processRepository;
public readonly Icopy _copy;
public Form1Factory(ILogger logger, ICopy copy)
{
this._processRepository = logger;
this._copy = copy;
}
public Form1 Create(int valueToEdit)
{
return new Form1(valueToEdit, _processRepository, _copy);
}
}
還有一個(gè)擴(kuò)展(Ninject.Extensions.Factory)允許您自動(dòng)生成工廠,例如Form1Factory基于接口的。如果您使用該擴(kuò)展名,則您聲明使用Bind<IForm1Factory>().ToFactory().

TA貢獻(xiàn)1862條經(jīng)驗(yàn) 獲得超7個(gè)贊
using Ninject;
using Ninject.Modules;
using Ninject.Parameters;
//Add new class
public class CompositionRoot
{
public static IKernel _ninjectKernel;
public static void Wire(INinjectModule module)
{
_ninjectKernel = new StandardKernel(module);
}
public static T Resolve<T>()
{
return _ninjectKernel.Get<T>();
}
public static T ResolveWithArgument<T>(ConstructorArgument argument)
{
return _ninjectKernel.Get<T>(argument);
}
}
//Ninject bindings
public class Bindings : NinjectModule
{
public override void Load()
{
Bind<ILogger>().To<LogToDB>();
Bind<ICopy>().To<CopyToFolder>();
}
}
//WinForm - Form1
public partial class Form1 : Form
{
public readonly ILogger _processRepository;
public readonly Icopy _copy;
public readonly int ValueToEdit;
public Form1(ILogger logger, ICopy copy, int valueToEdit)
{
this._processRepository = logger;
this._copy = copy;
this.ValueToEdit = valueToEdit;
InitializeComponent();
}
}
//main
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
//Apply the binding rule first
CompositionRoot.Wire(new Bindings());
//Then resolve your form dependencies this way using Ninject passing along the
constructor arguments.
CompositionRoot.ResolveWithArgument<Form1>(new ConstructorArgument("valueToEdit",
1)).ShowDialog();
}
- 2 回答
- 0 關(guān)注
- 120 瀏覽
添加回答
舉報(bào)