gpt4 book ai didi

c# - ActionFilterAttribute 的 Ninject 2 属性注入(inject)不起作用

转载 作者:太空狗 更新时间:2023-10-29 20:03:55 27 4
gpt4 key购买 nike

我有一个方法属性,它期望 Ninject 2 注入(inject)几个属性,但是 userSessionjobRepository 出现为 null:

[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class JobAttribute : ActionFilterAttribute {
[Inject]
private IUserSession userSession;

[Inject]
private IJobRepository jobRepository;

public override void OnActionExecuting(ActionExecutingContext filterContext) {
var filter = new JobFilter(userSession, jobRepository);

filter.OnActionExecuting(filterContext);
}
}

这是 Controller 中的方法:

[AcceptGet, Job]
public ActionResult Dimensions(Job job) {
return View(job.Building);
}

我知道我的设置工作正常,因为如果我在 Controller 上使用构造函数注入(inject), Controller 的参数就会被注入(inject)。尽管需要使用属性注入(inject),但这对我的属性没有太大帮助。我在这里遗漏了什么吗?

以下是 Global.asax.cs 的相关部分:

public class MvcApplication : Ninject.Web.Mvc.NinjectHttpApplication {
protected override void OnApplicationStarted() {
RegisterRoutes(RouteTable.Routes);
RegisterAllControllersIn(Assembly.GetExecutingAssembly());
}

...snip...

protected override IKernel CreateKernel() {
return new StandardKernel(
new RepositoryConfiguration(),
new AuthenticationModule(),
new AutoMapperConfiguration()
);
}
}

public class RepositoryConfiguration : NinjectModule {
public override void Load() {
Bind<ICustomerRepository>().To<CustomerRepository>();
Bind<IJobRepository>().To<JobRepository>();
}
}

public class AuthenticationModule : NinjectModule {
public override void Load() {
Bind<MbdQuote.Core.AppService.IUserSession>().To<UserSession>();
}
}

最佳答案

Ninject2 不进行字段注入(inject),将它们更改为具有公共(public) setter 的属性。

class JobAttribute : ActionFilterAttribute {
[Inject]
public IUserSession UserSession
{ set; private get; }

[Inject]
public IJobRepository JobRepository
{ set; private get; }
}

来自 Ninject 2 Beta announcement :

Things that were in Ninject 1.x that are not in Ninject 2:

  • Field injection: Ninject 2’s injection is now driven by expression trees, and in .NET 3.5 there is no way to set field values with an expression tree. Since this is a bad practice anyway, I decided to cut it.

关于c# - ActionFilterAttribute 的 Ninject 2 属性注入(inject)不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2269578/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com