如何将依赖项注入到 WCF 中的自定义 UserNamePasswordValidator 中?
我在 WCF 中使用 UserNamePasswordValidator 以及 Unity 进行依赖项注入,但由于 WCF 创建了 UserNamePasswordValidator 的实例,因此我无法将容器注入到该类中。那么我们该如何解决这个问题呢?
我能想到的最简单的解决方案是围绕 UnityContainer 的静态实例创建一个静态代理/包装类,它公开所有相同的方法......这样,任何类都可以访问容器,而我不需要到处注射它。
所以我可以在代码中的任何地方执行 UnityContainerWrapper.Resolve() 。所以基本上这个解决方案为我解决了两个问题,我可以在我没有创建实例的类中使用它,并且我可以在任何地方使用它,而不必将容器注入到一堆类中。
我能想到的唯一缺点是,我现在可能会将我的容器暴露给一堆以前无法访问容器的类。但不确定这是否是一个问题?
I'm using a UserNamePasswordValidator in WCF along with Unity for my dependency injection, but since WCF creates the instance of the UserNamePasswordValidator, I cannot inject my container into the class. So how would one go about this?
The simplest solution I can think of is to create a static proxy/wrapper class around a static instance of a UnityContainer, which exposes all the same methods... This way, any class can access the container, and I don't need to inject it everywhere.
So I could just do UnityContainerWrapper.Resolve() anywhere in code. So basically this solution solves 2 problems for me, I can use it in classes that I'm not creating an instance of, and I can use it anywhere without having to inject the container into a bunch of classes.
The only downside I can think of is that I'm now potentially exposing my container to a bunch of classes that wouldn't of had access to the container before. Not really sure if this is even a problem though?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,这个站点确实很糟糕,你应该避免它。在你的情况下,你可以这样做,
当创建服务主机时,它只会为服务创建一次,所以你应该编写以下代码,
这只是统一容器的静态包装器的颠倒想法:)
Yes, this downsite is realy bad, and you should avoid it. In your case you can do something like this
It will be created only once for service when service host is created, so you should write following code
This is just inverted idea with static wrapper of the unity container :)