我将服务层用作域模型层的外观,以编排对域对象的调用。我为我的 WCF 服务编写了一个自定义实例提供程序,以利用 MEF 创建实例。现在我需要应用 PIAB 进行审计和日志记录。我怎么能做到?
问问题
198 次
1 回答
0
Jimmy Tonner 写了一篇关于混合 MEF 和 PIAB 的精彩博客(请访问http://blogs.msdn.com/b/jimmytr/archive/2010/06/22/mixing-mef-and-piab.aspx)。它启发了我将 PIAB 应用于 MEFied WCF 服务的解决方案。想法很简单:首先使用 MEF 管理您的所有服务组合。然后在自定义实例提供者中,通过MEF容器定位到服务实例后应用PolicyInjection.Wrap。下面是代码示例:
服务:
[Export(typeof(ICustomerService))]
public class CustomerService : ICustomerService
{
#region ICustomerService Members
public Customer GetCustomer(string customerID)
{
return CustomerDAO.GetCustomer(customerID);
}
#endregion
}
自定义实例提供者:
public class PolicyInjectionInstanceProvider : IInstanceProvider
{
private Type serviceContractType;
private CompositionContainer Container { get; set; }
public PolicyInjectionInstanceProvider(Type t)
{
if (t!= null && !t.IsInterface)
{
throw new ArgumentException("Specified Type must be an interface");
}
this.serviceContractType = t;
}
#region IInstanceProvider Members
public object GetInstance(InstanceContext instanceContext, System.ServiceModel.Channels.Message message)
{
Type type = instanceContext.Host.Description.ServiceType;
if (serviceContractType != null)
{
Compose();
var importDefinition = new ImportDefinition(i => i.ContractName.Equals(serviceContractType.FullName), serviceContractType.FullName, ImportCardinality.ZeroOrMore, false, false);
var atomicComposition = new AtomicComposition();
IEnumerable<Export> extensions;
Container.TryGetExports(importDefinition, atomicComposition, out extensions);
if (extensions != null && extensions.Count() > 0)
{
var service = extensions.First().Value;
return PolicyInjection.Wrap(serviceContractType, service);
}
}
else
{
if (!type.IsMarshalByRef)
{
throw new ArgumentException("Type Must inherit MarshalByRefObject if no ServiceInterface is Specified");
}
return PolicyInjection.Create(type);
}
return null;
}
public object GetInstance(InstanceContext instanceContext)
{
return GetInstance(instanceContext, null);
}
public void ReleaseInstance(InstanceContext instanceContext, object instance)
{
var disposable = instance as IDisposable;
if (disposable != null)
{
disposable.Dispose();
}
Container.Dispose();
}
#endregion
#region Private Methods
private void Compose()
{
var catalog = new AggregateCatalog();
catalog.Catalogs.Add(new DirectoryCatalog(@".\")); //Extensions
Container = new CompositionContainer(catalog);
}
#endregion
}
于 2011-10-05T09:09:17.290 回答