简体   繁体   中英

Autofac passing properties to resolve

I've found how to register class with properties. But how can I make the same thing with runtime properties?

 builder.RegisterType<ClientProfile>()
        .WithProperty("Photos", new List<Photo>())
        .InstancePerLifetimeScope();

Something like this:

 var a = AutofacHostFactory.Container
                           .Resolve<ClientProfile>(
                               new NamedProperty ("id", user.Id), 
                               new NamedProperty ("UserName", user.UserName));

I think you have to extend your architecture a bit. What you are asking for is: how can a class know about "the current user"?

Well, you need to define a way for Autofac to provide a User.

For example, you could define an interface IUserService:

public interface IUserService
{
    User GetCurrentUser();
    User GetUser(String id);
}

Then implement it through a UserService (you can also skip the interface definition, if you really want to). As an example, the implementation could find the current user reading the db, the authentication cookie, the app.config, or whatever suits your scenario.

Then you register the UserService as IUserService, as usual.

Now you can define a constructor property of type IUserService and call GetCurrentUser() from it.

Or, you can register directly the User type:

builder.Register<User>(c => c.Resolve<IUserService>().GetCurrentUser()); 

Now you can just require a User from your components and access the properties from there. YMMV, but the pattern is going to be this: you need to define in some way a "UserContext".

Good luck!

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