简体   繁体   中英

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

I am new to Autofac and am researching different best practices. Per this Best Practices and Recommendations document, it is recommended that frequently used components should be registered using lambdas.

I have a concrete class, CurrentUser that implements IUserIdentity . This concrete class takes in HttpContextBase in order to retrieve the user's identity (id, roles, etc). My services obviously depend upon 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?

If so, how do I provide HttpContextBase since in my current code Autofac resolves it for me.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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