简体   繁体   English

我应该使用Lambda向Autofac注册每个请求的具体类吗?

[英]Should I register a per request concrete class using a lambda with Autofac?

I am new to Autofac and am researching different best practices. 我是Autofac的新手,正在研究不同的最佳实践。 Per this Best Practices and Recommendations document, it is recommended that frequently used components should be registered using lambdas. 根据此最佳做法和建议文档,建议应使用lambda注册经常使用的组件。

I have a concrete class, CurrentUser that implements IUserIdentity . 我有一个具体的类CurrentUser实现IUserIdentity This concrete class takes in HttpContextBase in order to retrieve the user's identity (id, roles, etc). 这个具体的类采用HttpContextBase来检索用户的身份(id,角色等)。 My services obviously depend upon IUserIdentity . 我的服务显然取决于IUserIdentity

I am currently registering this like this: 目前正在这样注册:

builder.RegisterType<CurrentUser>().As<IUserIdentity>().InstancePerRequest()

After reading this article, I am wondering if I should register it using a lambda since this will get resolved many times? 阅读本文后,我想知道是否应该使用lambda进行注册,因为它可以解决很多次?

If so, how do I provide HttpContextBase since in my current code Autofac resolves it for me. 如果是这样,我如何提供HttpContextBase因为在我当前的代码中Autofac会为我解决它。

I don't think you should worry about this unless you are actually optimizing your code, but in the event that you do still want to do it it would look something like this: 除非您实际上正在优化代码,否则我认为您不必为此担心,但是如果您仍然想要这样做,它将看起来像这样:

builder.Register(context => {
    var contextBase = context.Resolve<HttpContextBase>();
    return new CurrentUser(contextBase);
}).As<IUserIdentity>().InstancePerRequest();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM