나는이 목적으로 Autofac을 사용했습니다. 내 Global.asax.cs에서
public class LocationTypesController : ApiController
{
private readonly ILocationRepository _locationRepository;
private readonly IUnitOfWork _unitOfWork;
private readonly IAuthenticatedUser _user;
public LocationTypesController(ILocationRepository locationRepository,
IUnitOfWork unitOfWork,
IAuthenticatedUser user)
{
if (locationRepository == null)
throw new ArgumentNullException("locationRepository");
if (unitOfWork == null)
throw new ArgumentNullException("unitOfWork");
if (user == null)
throw new ArgumentNullException("user");
_locationRepository = locationRepository;
_unitOfWork = unitOfWork;
_user = user;
}
public IEnumerable<LocationType> Get()
{
try
{
IEnumerable<Location> locations = _locationRepository.GetAllAuthorizedLocations(_user.UserName);
_unitOfWork.Commit();
return locations.Select(location => location.LocationType).Distinct().OrderBy(location => location.LocationTypeId);
}
catch (Exception)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.BadRequest));
}
}
본질적으로 DI 프레임 워크를 활용하고 배치 매개 변수로 인터페이스를 사용자 저장소에 (또는 내 경우 WebApi 컨트롤러에) 내 컨트롤러에 다음
var builder = new ContainerBuilder();
builder.RegisterType<UnitOfWork>().As<IUnitOfWork>().InstancePerApiRequest();
builder.RegisterAssemblyTypes(typeof (LocationTypesRepository).Assembly).Where(
type => type.Name.EndsWith("Repository")).AsImplementedInterfaces();
및 파일 나는 다음과 같은 변경 한 제안을 바탕으로
[Ninject] (http://www.ninject.org/)는 매우 인기있는 DI 프레임 워크입니다. –
Ninject에 대해 알고 있지만 GenericRepository/UnitofWork를 컨트롤러에 주입하는 방법을 잘 모르는 경우 IUnitOfWork가 무엇인지 말해 줄 수 있습니까 ??? – Anurag
EF의 DBContext (Repository) ObjectContext (UnitOfWork) –