[英]Change autofac code on ninject
這是項目中的Autofac代碼
https://github.com/MarlabsInc/SocialGoal
如何在Ninject上更改此代碼?
我想使用社交目標項目中的存儲庫,但我更喜歡使用ninject而不是autofac。
public static class Bootstrapper
{
public static void Run()
{
SetAutofacContainer();
//Configure AutoMapper
AutoMapperConfiguration.Configure();
}
private static void SetAutofacContainer()
{
var builder = new ContainerBuilder();
builder.RegisterControllers(Assembly.GetExecutingAssembly());
builder.RegisterType<UnitOfWork>().As<IUnitOfWork>().InstancePerHttpRequest();
builder.RegisterType<DatabaseFactory>().As<IDatabaseFactory>().InstancePerHttpRequest();
builder.RegisterAssemblyTypes(typeof(FocusRepository).Assembly)
.Where(t => t.Name.EndsWith("Repository"))
.AsImplementedInterfaces().InstancePerHttpRequest();
builder.RegisterAssemblyTypes(typeof(GoalService).Assembly)
.Where(t => t.Name.EndsWith("Service"))
.AsImplementedInterfaces().InstancePerHttpRequest();
builder.RegisterAssemblyTypes(typeof(DefaultFormsAuthentication).Assembly)
.Where(t => t.Name.EndsWith("Authentication"))
.AsImplementedInterfaces().InstancePerHttpRequest();
builder.Register(c => new UserManager<ApplicationUser>(new UserStore<ApplicationUser>( new SocialGoalEntities())))
.As<UserManager<ApplicationUser>>().InstancePerHttpRequest();
builder.RegisterFilterProvider();
IContainer container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
}
}
通過將InRequestScope()
附加到綁定,可以在ninject中完成InstancePerHttpRequest
,如下所示:
kernel.Bind<IFoo>().To<UnitOfWork>().InRequestScope();
為了使InRequestScope
可用,您需要適當的Ninject.Web.Mvc*
nuget包,請參見此處 。 在stackoverflow上已經有幾篇文章介紹了這一點(如何為asp.net / MVC設置ninject)。
像RegisterAssemblyTypes
這樣的事情是使用Ninject.Extensions.Conventions完成的。 例:
builder.RegisterAssemblyTypes(typeof(FocusRepository).Assembly)
.Where(t => t.Name.EndsWith("Repository"))
.AsImplementedInterfaces().InstancePerHttpRequest();
完成如下:
kernel.Bind(x => x.From(typeof(FocusRepository).Assembly)
.IncludingNonePublicTypes() // only required if the classes aren't `public`
.SelectAllClasses()
.EndingWith("Repository")
.BindAllInterfaces()
.Configure(b => b.InRequestScope()));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.