私は次のクラスを持っています (私はそれらがうまく設計されていないことを知っています.Ninjectの問題を表現したいだけです).
コンストラクターの引数をサービスに渡す方法がわかりません (これは の依存Utility
関係ですMainProgram
):-
class MainProgram
{
static IKernel kernel;
static MainProgram mainProgram;
Utility Utility;
static void Main(string[] args)
{
kernel = new StandardKernel(new DIModule());
var constructorArgument1 = new ConstructorArgument("firstArg", args[0]);
var constructorArgument2 = new ConstructorArgument("secondArg", args[1]);
mainProgram = kernel.Get<MainProgram>(new IParameter[] { constructorArgument1, constructorArgument2 });
mainProgram.Utility.ExportToXML();
}
public MainProgram(Utility utility)
{
this.utility = utility;
}
}
public class Utility
{
private IService service;
public Utility(IService service)
{
this.service = service;
}
//methods to work with service
}
public class Service : IService
{
private readonly string firstArg;
private readonly string secondArg;
public Service(string firstArg, string secondArg)
{
this.firstArg = firstArg;
this.secondArg = secondArg;
}
}
class DIModule : NinjectModule
{
public override void Load()
{
Bind<IService>().To<Service>();
Bind<Utility>().ToSelf();
Bind<MainProgram>().ToSelf();
}
}
kernel.Get<MainProgram>()
は次のメッセージで失敗します。
文字列の有効化中にエラーが発生しました
No matching bindings are available, and the type is not self-bindable.
これは、コンストラクターの引数が IService に到達していないためだと理解しています。
これは私の依存関係を解決するための正しいアプローチでもありますか? いくつかの場所で、kernel.Get() を使用すると「DI を使用していない」と読みました。