Ninject.Web.Mvc2와 저장소 패턴 (엔티티 프레임 워크 모델을 기반으로 작성 됨)을 사용하는 MVC 2.0 응용 프로그램이 있습니다. 요청 기간 동안 만 살 수있는 새 ObjectContext를 만들려고합니다.Ninject PerRequest injection
는protected void Application_BeginRequest()
{
string EntityConnectionString = ConfigurationManager.ConnectionStrings["Entities"].ConnectionString;
HttpContext.Current.Items.Add(_PerRequestContextObjectKey, new EntityFrameworkContextWrapper(EntityConnectionString));
this.Kernel.Bind<IUserRepository>().To<UserRepository>().WithConstructorArgument("ContextWrapper", HttpContext.Current.Items[_PerRequestContextObjectKey]);
}
래퍼 클래스는 단지입니다 : 다음 나는 BeginRequest에서 작동하도록 설정 때문에 충분히이 일반적인 유지하기위한 아이디어가 부족
protected override IKernel CreateKernel(){
var kernel = new StandardKernel();
kernel.Load(Assembly.GetExecutingAssembly());
return kernel;
}
protected override void OnApplicationStarted()
{
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
}
: 나는 다음과 같은 방법으로이를 시도하고있다 요청이 끝나면 죽이고 싶은 것을 포함하는 일반적인 객체. 이 특정한 경우에, 그래서 내가 할 수있는 나의 새로운 ObjectContext를을 만들고도는 IDisposable을 구현하는 데 사용할 다음
protected void Application_EndRequest()
{
foreach (var Item in HttpContext.Current.Items)
{
if (Item.GetType() == typeof(IPerRequestLifetimeObjectWrapper))
{
(Item as IPerRequestLifetimeObjectWrapper).Dispose();
}
}
}
내가이 일의 예쁜 방법이 아니다 확신하지만,이 시점에서 내가 ' 나는이 모든 것을 "배우면서"많은 시간을 보냈기 때문에 움직이기 시작했다.
내 컨트롤러는 다음과 같이 주입 :
public class AdminUserController : Controller
{
// Mark for Ninject
[Inject] public IUserRepository _userRepo { get; set; }
public ViewResult Index()
{
return View(_userRepo.Get);
}
public ViewResult Edit(Guid UserUID)
{
return View(_userRepo.GetById(UserUID));
}
}
내 저장소뿐만 아니라 주입됩니다 :
[Inject]
public UserRepository(EntityFrameworkContextWrapper ContextWrapper)
// Mark for Ninject Dependency Injection
// Must receive Wrapper that contains active ObjectContext
{
_db = ContextWrapper.Entities; //Not actually named this, just easier for typing right now
}
을 내 컨트롤러 내 UserRepository 내부의 Get 메서드가 작동 처음 객체를 호출 할 때 큰. 새로 고침 (또는 포스트 백을 추측)을 수행하면 _db가 Null입니다. 디버거를 단계별로 시도 할 때 Application_BeginRequest()가 호출되기 전에 Controller Index() 메서드가 호출되고 있음을 알게되었습니다. 필자는 "파이프 라인"(WebForms에서 페이지 라이프 사이클을 호출하는 데 사용됨)에 대해 이해하고 있다고 생각했지만 지금은 약간 길다. 누군가 내 뇌에 몇 개의 전선이 교차되어있는 곳을 정교하게 해석 할 수 있습니까? 내가 말했듯이 이것은 아마도 가장 좋은 방법은 아니지만 MVC, Ninject, Repository 및 Entity Framework를 사용하는 DI를 배우기 위해 약 1 주일 정도 밖에 시간이 없었습니다. 나에게 아주 근본적인 걸 깨뜨린 것처럼 보인다면.
와 같은 당신이 BeginRequest에서'Bind'ing 수 야해 할 수 https://github.com/ninject/ninject.web.mvc/wiki/Unit-of-work-pattern-with-nhibernate
를 참조하십시오. 샘플을보고 모듈을 사용하여 모듈을 보관하거나 최소한 HttpApplication 당 한 번 수행하십시오. –