简体   繁体   English

Autofac传递属性来解决

[英]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. 好了,您需要定义Autofac提供用户的方式。

For example, you could define an interface IUserService: 例如,您可以定义一个接口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). 然后通过UserService实施它(如果您确实愿意,也可以跳过接口定义)。 As an example, the implementation could find the current user reading the db, the authentication cookie, the app.config, or whatever suits your scenario. 例如,该实现可以找到当前用户在读取db,身份验证cookie,app.config或适合您的情况的任何内容。

Then you register the UserService as IUserService, as usual. 然后,照常将UserService注册为IUserService。

Now you can define a constructor property of type IUserService and call GetCurrentUser() from it. 现在,您可以定义IUserService类型的构造函数属性,并从中调用GetCurrentUser()。

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. 现在,您只需要组件中的一个User即可从那里访问属性。 YMMV, but the pattern is going to be this: you need to define in some way a "UserContext". YMMV,但是模式将是这样:您需要以某种方式定义“ UserContext”。

Good luck! 祝好运!

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

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