附加属性统一

发布于 2024-11-03 09:20:16 字数 627 浏览 8 评论 0原文

我需要创建一个附加属性,它与其 PropertyChanged 事件处理程序内的某些服务进行通信。例如

private static void IsRegisteredPropertyChanged(DependencyObject target,
                                            DependencyPropertyChangedEventArgs e)
{
    //how to resolve this without service locator?
    IService someService = ServiceLocator.Resolve<IService>();

    if ((bool)e.NewValue)
    {
        someService.Register(target);
    }
    else
    {
        someService.Unregister(target);
    }
}

据我了解,事件处理程序将始终是静态的。除了服务定位器模式之外,是否有任何方法可以使用 Unity 注入此事件处理程序的依赖项?如果没有,那么也许有任何替代方案可以让您以声明方式将视图元素注册到该服务?

I need to create an attached property which communicates with some service inside it's PropertyChanged event handler. E. g.

private static void IsRegisteredPropertyChanged(DependencyObject target,
                                            DependencyPropertyChangedEventArgs e)
{
    //how to resolve this without service locator?
    IService someService = ServiceLocator.Resolve<IService>();

    if ((bool)e.NewValue)
    {
        someService.Register(target);
    }
    else
    {
        someService.Unregister(target);
    }
}

As I understand, the event handler will always be static. Is there any way to inject a dependency for this event handler using Unity except with Service Locator pattern? If not then maybe there are any alternatives that let you declaratively register view elements to that service?

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

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

发布评论

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

评论(1

老娘不死你永远是小三 2024-11-10 09:20:16

当涉及 static 关键字时,执行正确 DI 的唯一方法是通过方法注入

如果您可以通过方法参数之一注入服务,那么您就可以做到 - 否则您就不能。

您仍然可以使用服务定位器,但这不是 DI...

The only way to do proper DI when the static keyword is involved is through Method Injection.

If you can inject a service through one of the method parameters, you can do it - otherwise you can't.

You can still use a Service Locator, but that's not DI...

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