2 回答
TA贡献1831条经验 获得超4个赞
我想解决这个问题最干净的方法是创建一个工厂:
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);
}
}
还有一个扩展(Ninject.Extensions.Factory)允许您自动生成工厂,例如Form1Factory基于接口的。如果您使用该扩展名,则您声明使用Bind<IForm1Factory>().ToFactory().
TA贡献1862条经验 获得超7个赞
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 关注
- 74 浏览
添加回答
举报