使用autofac和WCF IParameterInspector进行IoC [英] IoC using autofac and WCF IParameterInspector

查看:65
本文介绍了使用autofac和WCF IParameterInspector进行IoC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在以下情况下使用autofac:
一个WCF服务,在每个方法调用上,该服务都会接收用于打开数据库连接的连接详细信息.
(即public UserDTO GetUser(string dbUsername, string dbPassword, int userId).

I'm trying to use autofac in the following scenario:
A WCF service that, on every method call, receives connection details which it uses to open a DB connection.
(i.e. public UserDTO GetUser(string dbUsername, string dbPassword, int userId).

由于打开数据库连接对于所有方法都是通用的,所以我想使用IParameterInspector来拦截每个方法调用,提取连接详细信息并初始化连接.

Since opening a DB connection is common to all methods, I'd like to use an IParameterInspector to intercept every method call, extract the connection details, and initialize the connection.

我的问题是-
1.我不知道是否可以(以及如何)将必要的工厂注入我的IParameterInspector
2.创建连接后,不确定如何在容器中注册它,以便该请求的所有组件都可以使用它.

My problems are-
1. I don't know if (and how) I can inject the necessary factory to my IParameterInspector
2. Once I've created my connection, I'm not sure as to how I can register it with my container so that it'll be available to all components for that request.

到目前为止,我的IParameterInspector:

        public object BeforeCall(string operationName, object[] inputs)
        {

            var userName = inputs[0] as Guid?;
            var password = inputs[1] as string;

            // How do I inject the ConnectionsFactory?
            var connection = ConnectionsFactory.CreateConnection(userName, password); 
           // How can I register my connection in the container, so that it'll be available to all dependencies created in this call?
            return null;
        }

谢谢

推荐答案

好,知道了-
我的问题是IParameterInspector在实例化我的服务类之后被调用.因此很明显,这不是进行初始化的地方.

Ok, figured it out-
My problem was that IParameterInspector was invoked after my service class was instanciated. So obviously that wasn't the place to do initializations.

实施IInstanceCreator被证明是正确的做法,因为它是在创建服务类之前 调用的,实际上它是用来告诉WCF如何创建服务类的.

Implementing a IInstanceCreator proved to be the right thing to do, since it's invoked before the creation of the service class, and is actually used to tell WCF how to create a service class.

我刚刚创建了一个autofac Lifetime Scope ,并向其注册了数据库连接.

I just created an autofac Lifetime Scope, and registered my DB Connection with it.

这篇关于使用autofac和WCF IParameterInspector进行IoC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆