I'm using:
- EF 4.1
- MVC 3
- Ninject
- Ninject.Extensions.Conventions
- Ninject.Web.Mvc
The app uses the repository pattern. My Repositories can be injected like this:
kernel.Bind<ICategoryRepository>().开发者_运维知识库To<CategoryRepository>().InRequestScope();
and it all works fine :-)
But i've neen attempting to go further with dynamically injecting from an asssembly like this in my global.asax.cs
private static void LoadFromAssemblies(IKernel kernel)
{
Uri uri = new Uri(
Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase) +
@"\Extensions");
DirectoryInfo directoryInfo = new DirectoryInfo(uri.LocalPath);
var scanner = new AssemblyScanner();
scanner.FromAssembliesInPath(directoryInfo.FullName);
scanner.BindWith<DefaultBindingGenerator>();
kernel.Scan(scanner);
//var foo = kernel.Get<ICategoryRepository>();
}
At run time the repository does get injected, but for some reason the entity never gets saved - perhaps because the repository can't tell if there are changes? or the unit of work is not maintained across the request?
My question is: How do i implement a "InRequestScope" when dynamically loading from assemblies? Do i have to somehow inject the kernel?
This approach (marked ***
) answers and solves the problem (copied from @John Barrett's comment):
kernel.Scan(a =>
{
a.FromAssembliesInPath(directoryInfo.FullName);
a.AutoLoadModules();
a.BindWithDefaultConventions();
a.InRequestScope(); // <-- ***
});
精彩评论