我爲此使用了Autofac。在我的Global.asax.cs文件
var builder = new ContainerBuilder();
builder.RegisterType<UnitOfWork>().As<IUnitOfWork>().InstancePerApiRequest();
builder.RegisterAssemblyTypes(typeof (LocationTypesRepository).Assembly).Where(
type => type.Name.EndsWith("Repository")).AsImplementedInterfaces();
,然後在我的控制器
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控制器)
[Ninject](http://www.ninject.org/)是一個非常流行的DI框架。 –
我知道Ninject,但不知道如何繼續它注入GenericRepository/UnitofWork到我的控制器,你能告訴我什麼是IUnitOfWork? – Anurag
EF –