你可以實現一個Autofac模塊具有AttachToComponentRegistration
方法,這將觸發針對每個註冊
public class XModule : Module
{
protected override void AttachToComponentRegistration(
IComponentRegistry componentRegistry, IComponentRegistration registration)
{
// do whatever you want with registration
}
}
的AttachToComponentRegistration
將觸發針對每個註冊:過去和未來。
Autofac.Extras.DynamicProxy2
擴展與RegistrationBuilder
一起使用,而Module
與Registration
一起使用。 AFAIK沒有辦法攔截 IRegistrationBuilder
並自動調用它的方法,因此沒有簡單的方法使用InterceptedBy
等方法在Module
上。
您可以順便做用經典Castle.Core攔截,而不依賴於Autofac.Extras.DynamicProxy2
像這樣的東西:
public class XModule : Module
{
public XModule()
{
this._generator = new ProxyGenerator();
}
private readonly ProxyGenerator _generator;
protected override void AttachToComponentRegistration(
IComponentRegistry componentRegistry,
IComponentRegistration registration)
{
if (registration.Services
.OfType<IServiceWithType>()
.Any(s => s.ServiceType == typeof(IApplicationService)))
{
registration.Activating += Registration_Activating;
}
}
private void Registration_Activating(Object sender, ActivatingEventArgs<Object> e)
{
Object proxy = this._generator.CreateClassProxyWithTarget(
e.Instance.GetType(),
e.Instance,
e.Context.Resolve<IEnumerable<IInterceptor>>().ToArray());
e.ReplaceInstance(proxy);
}
}
可以瀏覽Autofac.Extras.DynamicProxy2
模塊的source code瞭解您如何整合城堡。核心與Autofac。
我如何應用'InterceptedBy <>'將此批准應用到現有組件而不會覆蓋它? –
@OguzhanSoykan我編輯我的帖子,包括更多樣本 –
謝謝你的回答。我預測這個答案會出現:)我已經實施了這種方法,並且你告訴我在想什麼*沒有辦法攔截IRegistrationBuilder *。所以,我會將你的解決方案標記爲答案,但是,我認爲我們最終需要攔截* IRegistrationBuilder * –