如何使用unity IoC容器
我是 Unity IoC 容器的新手..我正在开发一个 WCF 应用程序(托管在 IIS 上)。我想使用Unity来注入记录器、数据库等对象...
据我所知,容器需要在应用程序启动时注册...我在WCF中哪里可以做到这一点?
设置完成后,如何在 WCF 应用程序中引用它?我的意思是我是否已将其设为静态或类似的东西?
Possible Duplicate:
Unity Dependency Injection for WCF services
Using Unity Dependency Injection with WCF services
I am new to Unity IoC Container.. I am working on a WCF application (hosted on IIS). I want to use Unity to inject objects like logger, database etc...
As far as I know, the container needs to registered at the application start-up... Where can I do that in WCF?
Once setup is done, how can I refer it across the WCF application? I mean do I have make it static or something like that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
WCF 以及任何其他基于 http 或基于请求的应用程序与标准 UI 应用程序明显不同。在应用程序收到第一个请求之前,IOC 容器的初始化不会发生,因此您必须采取一些不同的处理方式。
对于 IIS 中托管的标准 WCF 应用程序,最简单的方法是通过 HTTP 模块,该模块在第一次收到请求时初始化 Unity 容器。但是,如果您要正确执行操作,则应该研究自定义 InstanceProvider 类,该类将允许 Unity 提供 WCF 服务实现的实例,而不是使用 Unity 检索其依赖组件的单一 WCF 类。
我自己不太了解 Unity——我不喜欢 Ninject 和 StructureMap——但是一些快速的谷歌搜索导致了这个链接:http://initializecomponent.blogspot.com/2008/06/integrating-unity-with-wcf.html。看起来有人已经为您完成了这方面的大部分繁重工作。 :)
WCF, along with any other http- or request-based application, is distinctly different than a standard UI application. Initialization of your IOC container won't occur until the first request is received by your application, so you have to go about things a little differently.
For a standard WCF application hosted in IIS, the easiest way to do this would be through an HTTP module that initializes your Unity container the first time a request is received. If you're going to do things properly, however, you should investigate a custom InstanceProvider class that will allow Unity to provide the instance of the WCF service implementation, rather than having a singelton WCF class using Unity to retrieve its dependent components.
I don't know Unity very well, myself -- I prever Ninject and StructureMap -- but some quick googling resulted in this link: http://initializecomponent.blogspot.com/2008/06/integrating-unity-with-wcf.html. Looks like someone's already done most of the heavy lifting for you on this. :)