依赖注入 - 将 ninject di 转换为 lightinject di
dependency injection - convert ninject di to lightinject di
如何将以下 Ninject DI 转换为 LightInject DI 的等效项?我在获取正确语法方面遇到问题。
Database.SetInitializer(new MigrateDatabaseToLatestVersion<DefaultMembershipRebootDatabase, BrockAllen.MembershipReboot.Ef.Migrations.Configuration>());
kernel.Bind<UserAccountService>().ToSelf();
kernel.Bind<AuthenticationService>().To<SamAuthenticationService>();
kernel.Bind<IUserAccountQuery>().To<DefaultUserAccountRepository>().InRequestScope();
kernel.Bind<IUserAccountRepository>().To<DefaultUserAccountRepository>().InRequestScope();
在我原来的问题上,我没有包括这个,但是这个(也 post 编辑为对此 post 的评论)是我试图让它工作的无效代码:
Database.SetInitializer(new MigrateDatabaseToLatestVersion<DefaultMembershipRebootDatabase, BrockAllen.MembershipReboot.Ef.Migrations.Configuration>());
container.Register<UserAccountService>();
container.Register<AuthenticationService, SamAuthenticationService>();
container.Register<IUserAccountQuery, DefaultUserAccountRepository>(new PerRequestLifeTime());
container.Register<IUserAccountRepository, DefaultUserAccountRepository>(new PerRequestLifeTime());
给出的错误消息(没有堆栈跟踪)是这样的:
异常详细信息:System.InvalidOperationException:未解决的依赖项[目标类型:BrockAllen.MembershipReboot.Ef.DefaultUserAccountRepository]、[参数:ctx(BrockAllen.MembershipReboot.Ef.DefaultMembershipRebootDatabase)]、[请求的依赖项:ServiceType:BrockAllen。 MembershipReboot.Ef.DefaultMembershipRebootDatabase,服务名称:]
来源错误:
在执行当前网络请求期间产生了未处理的异常。可以使用下面的异常堆栈跟踪来识别有关异常来源和位置的信息。
*如果有人也想查看堆栈跟踪 - * 只需询问,我会 post 回复此问题。
DefaultMembershipRebootDatabase 的构造函数(在示例项目中,我的项目使用了通过 nuget 提供的 dll,并且构造函数不可用,但我很确定它们在两者中很可能相同案例(看它如何来自同一来源...)是:
public class DefaultMembershipRebootDatabase : MembershipRebootDbContext<RelationalUserAccount>
{
public DefaultMembershipRebootDatabase()
: base()
{
}
public DefaultMembershipRebootDatabase(string nameOrConnectionString)
: base(nameOrConnectionString)
{
}
public DefaultMembershipRebootDatabase(string nameOrConnectionString, string schemaName)
: base(nameOrConnectionString, schemaName)
{
}
}
这是 DefaultUserAccountRepository 的构造函数(与上述示例项目相同):
public class DefaultUserAccountRepository
: DbContextUserAccountRepository<DefaultMembershipRebootDatabase, RelationalUserAccount>,
IUserAccountRepository
{
public DefaultUserAccountRepository(DefaultMembershipRebootDatabase ctx)
: base(ctx)
{
}
IUserAccountRepository<RelationalUserAccount> This { get { return (IUserAccountRepository<RelationalUserAccount>)this; } }
public new UserAccount Create()
{
return This.Create();
}
public void Add(UserAccount item)
{
This.Add((RelationalUserAccount)item);
}
public void Remove(UserAccount item)
{
This.Remove((RelationalUserAccount)item);
}
public void Update(UserAccount item)
{
This.Update((RelationalUserAccount)item);
}
public new UserAccount GetByID(System.Guid id)
{
return This.GetByID(id);
}
public new UserAccount GetByUsername(string username)
{
return This.GetByUsername(username);
}
UserAccount IUserAccountRepository<UserAccount>.GetByUsername(string tenant, string username)
{
return This.GetByUsername(tenant, username);
}
public new UserAccount GetByEmail(string tenant, string email)
{
return This.GetByEmail(tenant, email);
}
public new UserAccount GetByMobilePhone(string tenant, string phone)
{
return This.GetByMobilePhone(tenant, phone);
}
public new UserAccount GetByVerificationKey(string key)
{
return This.GetByVerificationKey(key);
}
public new UserAccount GetByLinkedAccount(string tenant, string provider, string id)
{
return This.GetByLinkedAccount(tenant, provider, id);
}
public new UserAccount GetByCertificate(string tenant, string thumbprint)
{
return This.GetByCertificate(tenant, thumbprint);
}
}
这是我项目中的控制器:
namespace brockallen_MembershipReboot.Controllers
{
using System.ComponentModel.DataAnnotations;
using BrockAllen.MembershipReboot;
using BrockAllen.MembershipReboot.Mvc.Areas.UserAccount.Models;
public class UserAccountController : Controller
{
UserAccountService _userAccountService;
AuthenticationService _authService;
public UserAccountController(AuthenticationService authService)
{
_userAccountService = authService.UserAccountService;
_authService = authService;
}
// GET: /UserAccount/
[Authorize]
public ActionResult Index()
{
return View();
}
public ActionResult Login()
{
return View(new LoginInputModel());
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginInputModel model)
{
if (ModelState.IsValid)
{
/*BrockAllen.MembershipReboot.*/UserAccount account;
if (_userAccountService.AuthenticateWithUsernameOrEmail(model.Username, model.Password, out account))
{
_authService.SignIn(account, model.RememberMe);
_authService.SignIn(account, model.RememberMe);
/*if (account.RequiresTwoFactorAuthCodeToSignIn())
{
return RedirectToAction("TwoFactorAuthCodeLogin");
}
if (account.RequiresTwoFactorCertificateToSignIn())
{
return RedirectToAction("CertificateLogin");
}
if (_userAccountService.IsPasswordExpired(account))
{
return RedirectToAction("Index", "ChangePassword");
}*/
if (Url.IsLocalUrl(model.ReturnUrl))
{
return Redirect(model.ReturnUrl);
}
return RedirectToAction("Index");
}
else
{
ModelState.AddModelError("", "Invalid Username or Password");
}
}
return View(model);
}
public ActionResult Register()
{
return View(new RegisterInputModel());
}
[ValidateAntiForgeryToken]
[HttpPost]
public ActionResult Register(RegisterInputModel model)
{
if (ModelState.IsValid)
{
try
{
var account = _userAccountService.CreateAccount(model.Username, model.Password, model.Email);
ViewData["RequireAccountVerification"] = _userAccountService.Configuration.RequireAccountVerification;
return View("Success", model);
}
catch (ValidationException ex)
{
ModelState.AddModelError("", ex.Message);
}
}
return View(model);
}
}
}
AuthenicationService 的构造函数是:
public abstract class AuthenticationService : AuthenticationService<UserAccount>
{
public new UserAccountService UserAccountService
{
get { return (UserAccountService)base.UserAccountService; }
set { base.UserAccountService = value; }
}
public AuthenticationService(UserAccountService userService)
: this(userService, null)
{
}
public AuthenticationService(UserAccountService userService, ClaimsAuthenticationManager claimsAuthenticationManager)
: base(userService, claimsAuthenticationManager)
{
}
}
默认情况下,LightInject 不解析具体的 classes 而不注册它们,而 NInject 会。
例如NInject可以在不注册的情况下解析DefaultMembershipRebootDatabase
,而LightInject默认不能。看看this.
无论如何,要解决您的问题,请确保注册您的具体 classes(在其他 classes 中需要作为依赖项)。这是一个例子:
container.Register<DefaultMembershipRebootDatabase>();
我在这里假设某些 class 依赖于具体的 class DefaultMembershipRebootDatabase
。如果您有其他具体的 class 依赖项,请确保您也注册了它们。
您应该使用 PerScopeLifetime 而不是 PerRequestLifetime。 PerRequestLifetime 代表一个短暂的生命周期,它跟踪一次性实例并在范围结束时处置它们。 PerScopeLifetime 确保范围内的相同实例,在这种情况下意味着 Web 请求中的相同实例。
如何将以下 Ninject DI 转换为 LightInject DI 的等效项?我在获取正确语法方面遇到问题。
Database.SetInitializer(new MigrateDatabaseToLatestVersion<DefaultMembershipRebootDatabase, BrockAllen.MembershipReboot.Ef.Migrations.Configuration>());
kernel.Bind<UserAccountService>().ToSelf();
kernel.Bind<AuthenticationService>().To<SamAuthenticationService>();
kernel.Bind<IUserAccountQuery>().To<DefaultUserAccountRepository>().InRequestScope();
kernel.Bind<IUserAccountRepository>().To<DefaultUserAccountRepository>().InRequestScope();
在我原来的问题上,我没有包括这个,但是这个(也 post 编辑为对此 post 的评论)是我试图让它工作的无效代码:
Database.SetInitializer(new MigrateDatabaseToLatestVersion<DefaultMembershipRebootDatabase, BrockAllen.MembershipReboot.Ef.Migrations.Configuration>());
container.Register<UserAccountService>();
container.Register<AuthenticationService, SamAuthenticationService>();
container.Register<IUserAccountQuery, DefaultUserAccountRepository>(new PerRequestLifeTime());
container.Register<IUserAccountRepository, DefaultUserAccountRepository>(new PerRequestLifeTime());
给出的错误消息(没有堆栈跟踪)是这样的:
异常详细信息:System.InvalidOperationException:未解决的依赖项[目标类型:BrockAllen.MembershipReboot.Ef.DefaultUserAccountRepository]、[参数:ctx(BrockAllen.MembershipReboot.Ef.DefaultMembershipRebootDatabase)]、[请求的依赖项:ServiceType:BrockAllen。 MembershipReboot.Ef.DefaultMembershipRebootDatabase,服务名称:]
来源错误:
在执行当前网络请求期间产生了未处理的异常。可以使用下面的异常堆栈跟踪来识别有关异常来源和位置的信息。
*如果有人也想查看堆栈跟踪 - * 只需询问,我会 post 回复此问题。
DefaultMembershipRebootDatabase 的构造函数(在示例项目中,我的项目使用了通过 nuget 提供的 dll,并且构造函数不可用,但我很确定它们在两者中很可能相同案例(看它如何来自同一来源...)是:
public class DefaultMembershipRebootDatabase : MembershipRebootDbContext<RelationalUserAccount>
{
public DefaultMembershipRebootDatabase()
: base()
{
}
public DefaultMembershipRebootDatabase(string nameOrConnectionString)
: base(nameOrConnectionString)
{
}
public DefaultMembershipRebootDatabase(string nameOrConnectionString, string schemaName)
: base(nameOrConnectionString, schemaName)
{
}
}
这是 DefaultUserAccountRepository 的构造函数(与上述示例项目相同):
public class DefaultUserAccountRepository
: DbContextUserAccountRepository<DefaultMembershipRebootDatabase, RelationalUserAccount>,
IUserAccountRepository
{
public DefaultUserAccountRepository(DefaultMembershipRebootDatabase ctx)
: base(ctx)
{
}
IUserAccountRepository<RelationalUserAccount> This { get { return (IUserAccountRepository<RelationalUserAccount>)this; } }
public new UserAccount Create()
{
return This.Create();
}
public void Add(UserAccount item)
{
This.Add((RelationalUserAccount)item);
}
public void Remove(UserAccount item)
{
This.Remove((RelationalUserAccount)item);
}
public void Update(UserAccount item)
{
This.Update((RelationalUserAccount)item);
}
public new UserAccount GetByID(System.Guid id)
{
return This.GetByID(id);
}
public new UserAccount GetByUsername(string username)
{
return This.GetByUsername(username);
}
UserAccount IUserAccountRepository<UserAccount>.GetByUsername(string tenant, string username)
{
return This.GetByUsername(tenant, username);
}
public new UserAccount GetByEmail(string tenant, string email)
{
return This.GetByEmail(tenant, email);
}
public new UserAccount GetByMobilePhone(string tenant, string phone)
{
return This.GetByMobilePhone(tenant, phone);
}
public new UserAccount GetByVerificationKey(string key)
{
return This.GetByVerificationKey(key);
}
public new UserAccount GetByLinkedAccount(string tenant, string provider, string id)
{
return This.GetByLinkedAccount(tenant, provider, id);
}
public new UserAccount GetByCertificate(string tenant, string thumbprint)
{
return This.GetByCertificate(tenant, thumbprint);
}
}
这是我项目中的控制器:
namespace brockallen_MembershipReboot.Controllers
{
using System.ComponentModel.DataAnnotations;
using BrockAllen.MembershipReboot;
using BrockAllen.MembershipReboot.Mvc.Areas.UserAccount.Models;
public class UserAccountController : Controller
{
UserAccountService _userAccountService;
AuthenticationService _authService;
public UserAccountController(AuthenticationService authService)
{
_userAccountService = authService.UserAccountService;
_authService = authService;
}
// GET: /UserAccount/
[Authorize]
public ActionResult Index()
{
return View();
}
public ActionResult Login()
{
return View(new LoginInputModel());
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginInputModel model)
{
if (ModelState.IsValid)
{
/*BrockAllen.MembershipReboot.*/UserAccount account;
if (_userAccountService.AuthenticateWithUsernameOrEmail(model.Username, model.Password, out account))
{
_authService.SignIn(account, model.RememberMe);
_authService.SignIn(account, model.RememberMe);
/*if (account.RequiresTwoFactorAuthCodeToSignIn())
{
return RedirectToAction("TwoFactorAuthCodeLogin");
}
if (account.RequiresTwoFactorCertificateToSignIn())
{
return RedirectToAction("CertificateLogin");
}
if (_userAccountService.IsPasswordExpired(account))
{
return RedirectToAction("Index", "ChangePassword");
}*/
if (Url.IsLocalUrl(model.ReturnUrl))
{
return Redirect(model.ReturnUrl);
}
return RedirectToAction("Index");
}
else
{
ModelState.AddModelError("", "Invalid Username or Password");
}
}
return View(model);
}
public ActionResult Register()
{
return View(new RegisterInputModel());
}
[ValidateAntiForgeryToken]
[HttpPost]
public ActionResult Register(RegisterInputModel model)
{
if (ModelState.IsValid)
{
try
{
var account = _userAccountService.CreateAccount(model.Username, model.Password, model.Email);
ViewData["RequireAccountVerification"] = _userAccountService.Configuration.RequireAccountVerification;
return View("Success", model);
}
catch (ValidationException ex)
{
ModelState.AddModelError("", ex.Message);
}
}
return View(model);
}
}
}
AuthenicationService 的构造函数是:
public abstract class AuthenticationService : AuthenticationService<UserAccount>
{
public new UserAccountService UserAccountService
{
get { return (UserAccountService)base.UserAccountService; }
set { base.UserAccountService = value; }
}
public AuthenticationService(UserAccountService userService)
: this(userService, null)
{
}
public AuthenticationService(UserAccountService userService, ClaimsAuthenticationManager claimsAuthenticationManager)
: base(userService, claimsAuthenticationManager)
{
}
}
默认情况下,LightInject 不解析具体的 classes 而不注册它们,而 NInject 会。
例如NInject可以在不注册的情况下解析DefaultMembershipRebootDatabase
,而LightInject默认不能。看看this.
无论如何,要解决您的问题,请确保注册您的具体 classes(在其他 classes 中需要作为依赖项)。这是一个例子:
container.Register<DefaultMembershipRebootDatabase>();
我在这里假设某些 class 依赖于具体的 class DefaultMembershipRebootDatabase
。如果您有其他具体的 class 依赖项,请确保您也注册了它们。
您应该使用 PerScopeLifetime 而不是 PerRequestLifetime。 PerRequestLifetime 代表一个短暂的生命周期,它跟踪一次性实例并在范围结束时处置它们。 PerScopeLifetime 确保范围内的相同实例,在这种情况下意味着 Web 请求中的相同实例。