接口成员的属性注入

发布于 2024-11-24 00:39:54 字数 764 浏览 2 评论 0原文

我可以使用以下代码进行属性注入:

builder.RegisterType<ListViewModel>()
    .PropertiesAutowired();

这会注入所有属性的依赖项。但有时我只想为接口的成员进行属性注入:

public interface IHasCommonServices
{
    ISession Session { get; set; }
    IEventPublisher EventPublisher { get; set; }
}

public class ListViewModel : IHasCommonServices
{
    // Inject dependencies for these properties
    public ISession Session { get; set; }
    public IEventPublisher EventPublisher { get; set; }

    // Don't inject for these properties
    public ListItemViewModel SelectedItem { get; set; }
}

是否可以执行以下操作?

builder.RegisterType<ListViewModel>()
    .InjectForInterface<IHasCommonServices>();

谢谢。

I can do property injection by using the following code:

builder.RegisterType<ListViewModel>()
    .PropertiesAutowired();

This injects dependencies for all properties. But sometimes I only want to do property injection for members of an interface:

public interface IHasCommonServices
{
    ISession Session { get; set; }
    IEventPublisher EventPublisher { get; set; }
}

public class ListViewModel : IHasCommonServices
{
    // Inject dependencies for these properties
    public ISession Session { get; set; }
    public IEventPublisher EventPublisher { get; set; }

    // Don't inject for these properties
    public ListItemViewModel SelectedItem { get; set; }
}

Is something like the following possible?

builder.RegisterType<ListViewModel>()
    .InjectForInterface<IHasCommonServices>();

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

生生漫 2024-12-01 00:39:54

不确定这是否是您想要的,但我认为在大多数情况下您可以逃脱:

.PropertiesAutowired(PropertyWiringFlags.PreserveSetValues);

如果您需要更细粒度的控制,您可以使用 OnActivated:

builder.Register<ListViewModel>()
       .As<IHasCommonServices>()
       .OnActivated(c => 
                    {
                        c.Instance.Session = c.Context.Resolve<ISession>();
                        c.Instance.EventPublisher = c.Context.Resolve<IEventPublisher>();
                    });

这有点乏味,但我不这样做我认为您不会经常需要进行大量的财产注入。

希望有帮助。

Not sure if this is what you're after, but I think in most cases you can get away with:

.PropertiesAutowired(PropertyWiringFlags.PreserveSetValues);

If you need to have a bit more fine-grained control you can use OnActivated:

builder.Register<ListViewModel>()
       .As<IHasCommonServices>()
       .OnActivated(c => 
                    {
                        c.Instance.Session = c.Context.Resolve<ISession>();
                        c.Instance.EventPublisher = c.Context.Resolve<IEventPublisher>();
                    });

It's a little-bit tedious, but I don't think you would often need to do much property injection.

Hope that helps.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文