我有一个通过MEF使用DI的WCF服务。那部分工作正常。 我也有一个Custom UserNamePasswordValidator,只要我使用无参数构造函数和'new'一切就可以工作。不过我也想介绍MEF。
该服务托管在IIS中,因此我必须稍微拦截它以使MEF按原样运行。 我在下面提供了我的代码的横截面,我们将不胜感激任何帮助!
这是我的web.config: -
<behavior name="StandardServiceBehaviour">
<serviceDebug includeExceptionDetailInFaults="true" />
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Custom"
customUserNamePasswordValidatorType=
"WebService.Validators.CustomUserNamePasswordValidator, WebService" />
</serviceCredentials>
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<dataContractSerializer maxItemsInObjectGraph="67108864" />
</behavior>
我的自定义验证器如下: -
[Export(typeof(ICustomUserNamePasswordValidator))]
[PartCreationPolicy(CreationPolicy.Shared)]
public class CustomUserNamePasswordValidator : UserNamePasswordValidator, ICustomUserNamePasswordValidator
{
[ImportingConstructor]
public CustomUserNamePasswordValidator([NotNull] IConnectionProvider connectionProvider)
{
}
.....
}
我在我的Web服务上使用一个名为WebServiceExport的自定义属性,该属性是MEF Export属性的子类,包含一个InstanceProvider: -
[WebServiceExport(typeof(IGeneralService))]
public class GeneralService : IGeneralService
{
....
}
这是导出属性: -
public class WebServiceExportAttribute : ExportAttribute, IContractBehavior, IContractBehaviorAttribute
{
public void ApplyDispatchBehavior(ContractDescription description, ServiceEndpoint endpoint, DispatchRuntime dispatch)
{
var contractType = description.ContractType;
dispatch.InstanceProvider = new MefInstanceProvider(contractType);
}
....
}
最后这是实例提供者: -
public class MefInstanceProvider : IInstanceProvider
{
public MefInstanceProvider(Type serviceContract)
{
_serviceContract = serviceContract;
}
public object GetInstance(InstanceContext instanceContext, Message message)
{
BuildInstance(); //compose MEF parts
}
....
}