我正在使用mvc web api。我有一個通用的IRepository和IUnitOfWork庫,它在asp.net mvc中很完美,但是當我打算在我的mvc web api項目中使用它時,我的存儲庫對象變爲null,從而導致異常。我的存儲庫和的UnitOfWork對象被實例化和構造函數那樣的把一個IunitOfWork
對象作爲參數確定在MVC Web API中調用操作時調用哪個構造函數(更改默認構造函數)
這裏內部初始化是代碼(構造函數代碼)
private IRepository<AspNetUserAccount> AccountRepository;
private IRepository<Doctor> DoctorRepository;
private readonly IUnitOfWork UnitOfWork;
public AccountController(IUnitOfWork unitOfWork)
{
UnitOfWork = unitOfWork;
AccountRepository = unitOfWork.Repository<AspNetUserAccount>();
DoctorRepository = unitOfWork.Repository<Doctor>();
}
public AccountController()
{
}
這裏是我庫和的UnitOfWork的使用對象Register
控制器的動作Account
。
[AllowAnonymous]
[Route("Register")]
public ResultViewModel Register([FromBody]UserBindingModel model)
{
if (!ModelState.IsValid)
{
return new ResultViewModel(400, "Model Is Not Valid");
}
using (DigiTebDBContext db = new DigiTebDBContext())
{
using (var Transaction = db.Database.BeginTransaction())
{
try
{
var user = new ApplicationUser()
{
UserName = model.UserName,
Email = model.Email
,
CreateTimeStamp = DateTime.Now,
LastModifiedTimeStamp = DateTime.Now
};
IdentityResult result = UserManager.Create(user, model.Password);
if (!result.Succeeded)
throw new Exception(((string[])result.Errors)[0]);
UserUtility.AssignRoleToUser(user.Id, "Operator");
var Account = new AspNetUserAccount
{
AccountTypeValue = AccountType.Demo,
CreateTimeStamp = DateTime.Now
,
CreateUserId = user.Id,
CurrentUserCount = 0,
MaxUserCount = 1,
IsMultiUser = false
,
ExpiryDate = DateTime.Now,
LastModifiedUserId = user.Id,
LastModifiedTimeStamp = DateTime.Now
};
AccountRepository.Insert(Account);
UnitOfWork.Save();
Transaction.Commit();
return new ResultViewModel(200, "Registeration was successfull");
}
catch(Exception ex)
{
Transaction.Rollback();
return new ResultViewModel(400, ex.Message);
}
finally
{
UnitOfWork.Dispose();
}
}
}
我的問題是,我的倉庫(AccountRepository)
和的UnitOfWork (UnitOfWork)
對象被實例化,並在一個永遠不會被稱爲構造函數初始化。 當一個動作被調用時(不管是什麼)只有無參數的構造函數被調用,而不是我想要的構造函數帶有一個參數。
如何更改它,以便調用所需的構造函數而不是默認的無參數構造函數,換句話說如何確定在mvc web api中調用動作時調用哪個構造函數??
我搜索了一下它,我發現我可以使用DI來解決這個問題,我使用Ninject,但我不知道如何以及在哪裏我應該寫我的代碼(使用Ninject)來更改我Account
類(控制器)的默認構造函數,並將其設置爲另一個構造
這裏是我在NinjectWebCommon.cs
Ninject修改在App_Start
文件夾
private static IKernel CreateKernel()
{
var kernel = new StandardKernel();
try
{
kernel.Bind<Func<IKernel>>().ToMethod(ctx =>() => new Bootstrapper().Kernel);
kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
RegisterServices(kernel);
return kernel;
}
catch
{
kernel.Dispose();
throw;
}
}
private static void RegisterServices(IKernel kernel)
{
kernel.Bind(typeof(IRepository<AspNetUserAccount>)).To(typeof(Repository<AspNetUserAccount>)).InRequestScope();
kernel.Bind(typeof(IDataContext)).To(typeof(DigiTebDBContext)).InRequestScope();
kernel.Bind(typeof(IUnitOfWork)).To(typeof(UnitOfWork)).InRequestScope();
kernel.Bind<HttpContext>().ToMethod(ctx => HttpContext.Current).InTransientScope();
}
在此先感謝
框架的默認控制器工廠使用無參數構造函數。查找'DependencyResolver' – Nkosi