私はNinjectが初めてで、stackoverflowも初めてです。
ninject.web.mvc 拡張機能で使用しています。次のように正しく初期化できました。
public class MvcApplication : NinjectHttpApplication
{
protected override void OnApplicationStarted()
{
RegisterRoutes(RouteTable.Routes);
}
protected override IKernel CreateKernel()
{
var kernel = new StandardKernel();
kernel.Load(AssemblyLocator.GetBinFolderAssemblies());
return kernel;
}
}
そして、bin フォルダー内のすべてのアセンブリをスキャンし、アセンブリ内のすべての Ninject モジュールを検索するクラス assemlylocator を次に示します。
public static class AssemblyLocator
{
private static readonly ReadOnlyCollection AllAssemblies = null;
private static readonly ReadOnlyCollection BinFolderAssemblies = null;
static AssemblyLocator()
{
AllAssemblies = new ReadOnlyCollection<Assembly>(
BuildManager.GetReferencedAssemblies().Cast<Assembly>().ToList());
IList<Assembly> binFolderAssemblies = new List<Assembly>();
string binFolder = HttpRuntime.AppDomainAppPath + "bin\\";
IList<string> dllFiles = Directory.GetFiles(binFolder, "*.dll",
SearchOption.TopDirectoryOnly).ToList();
foreach (string dllFile in dllFiles)
{
AssemblyName assemblyName = AssemblyName.GetAssemblyName(dllFile);
Assembly locatedAssembly = AllAssemblies.FirstOrDefault(a =>
AssemblyName.ReferenceMatchesDefinition(a.GetName(), assemblyName));
if (locatedAssembly != null)
{
binFolderAssemblies.Add(locatedAssembly);
}
}
BinFolderAssemblies = new ReadOnlyCollection<Assembly> (binFolderAssemblies);
}
public static ReadOnlyCollection<Assembly> GetAssemblies()
{
return AllAssemblies;
}
public static ReadOnlyCollection<Assembly> GetBinFolderAssemblies()
{
return BinFolderAssemblies;
}
}
すべてが私のコントローラーで正常に動作します:
public class ReteController : Controller
{ // // GET: /Rete/
private readonly IReteService _service;
public ReteController(IReteService _service)
{
if (_service == null)
{
throw new ArgumentNullException("IReteService");
}
this._service = _service;
}
public ActionResult Index()
{
return View(_service.getReti());
}
ここまでは、ほとんどすべてを簡単に習得できましたが、今の問題は、Ninject から NinjectModule にバインドされたオブジェクトの新しいインスタンスを作成する必要がある場合、heare からカーネルにアクセスする方法がわからないことです。
//this is jus a ex.
public ActionResult NewRete() {
IRete xItem = Kernel.get();
xItem.name= "hope";
return View(xItem);
}
問題は、コントローラーからカーネルを見つけることができないことです。コンストラクターにも注入する必要がありますか??
誰かが私を助けてくれることを願っています。皆さんが私に与えてくれた大きな助けに感謝します。