WCF 和 Unity - 依赖注入
我正在尝试通过依赖注入来连接 WCF。我发现的所有示例都基于以下假设:您使用 .svc (ServiceHostFactory) 服务或使用 app.config 来配置容器。其他示例也基于将容器传递给类。
我想要一个容器不被传递的解决方案(不与 Unity 紧密耦合)。我不使用配置文件来配置容器,而我使用自托管服务。
问题是 - 正如我所见 - ServiceHost 将服务实现的类型作为参数,那么使用 InstanceProvider 有什么不同呢?
我目前提出的解决方案是注册 ServiceHost (或专业化)并注册一个带有名称的类型(例如 container.RegisterInstance
container.RegisterInstance
然后 container.RegisterType
有更好的解决方案吗?我也许是在我的假设中,
迈克尔
I'm trying to hock up WCF with dependency injection. All the examples that I have found is based on the assumptions that you either uses a .svc (ServiceHostFactory) service or uses app.config to configure the container. Other examples is also based on that the container is passed around to the classes.
I would like a solution where the container is not passed around (not tightly coupled to Unity). Where I don't uses a config file to configure the container and where I use self-hosted services.
The problem is - as I see it - that the ServiceHost is taking the type of the service implementation as a parameter so what different does it do to use the InstanceProvider?
The solution I have come up with at the moment is to register the ServiceHost (or a specialization) an register a Type with a name ( e.g. container.RegisterInstance<Type>("ServiceName", typeof(Service);
).
And then container.RegisterType<UnityServiceHost>(new InjectionConstructor(new ResolvedParameter<Type>("ServiceName")));
to register the ServiceHost.
Any better solutions out there? I'm I perhaps way of in my assumptions.
Best regards,
Michael
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用构造函数注入来连接您的服务实现,就像使用任何其他类一样。
这是关于如何让WCF理解构造函数注入。
该答案中的示例演示了穷人注入,但您可以从中推断并在 ServiceHostFactory 中设置 UnityContainer 实例,而不是硬编码的依赖项。
您将容器实例一直传递给自定义 IInstanceProvider。现在您可以在 GetInstance 方法中使用容器:
Use Constructor Injection to wire up your service implementation, just like you would with any other class.
Here's a writeup on how to make WCF understand Constructor Injection.
The example in that answer demonstrates Poor Man's Injection, but you can extrapolate from it and set up your UnityContainer instance in the ServiceHostFactory instead of a hard-coded dependency.
You pass the container instance all the way to the custom IInstanceProvider. Now you can use the container in the GetInstance method: