, .. Autofac.Module, . .
EnableInterfaceInterceptors . .
. , , . ( -):
public interface IInterface
{
void DoWork();
}
public class Implementation : IInterface
{
public void DoWork()
{
Console.WriteLine("Implementation doing work.");
}
}
public class CallLogger : IInterceptor
{
TextWriter _output;
public CallLogger(TextWriter output)
{
_output = output;
}
public void Intercept(IInvocation invocation)
{
_output.WriteLine("Calling method {0} with parameters {1}... ",
invocation.Method.Name,
string.Join(", ", invocation.Arguments.Select(a => (a ?? "").ToString()).ToArray()));
invocation.Proceed();
_output.WriteLine("Done: result was {0}.", invocation.ReturnValue);
}
}
( ) . , Autofac.Module, Autofac , .
: , " " . , , , , , sorta-kinda "-", . .
, . :
public class InterceptorModule : Autofac.Module
{
const string InterceptorsPropertyName = "Autofac.Extras.DynamicProxy2.RegistrationExtensions.InterceptorsPropertyName";
protected override void Load(ContainerBuilder builder)
{
builder.Register(c => new CallLogger(Console.Out));
}
protected override void AttachToComponentRegistration(IComponentRegistry componentRegistry, IComponentRegistration registration)
{
var interceptorServices = new Service[] { new TypedService(typeof(CallLogger)) };
object existing;
if (registration.Metadata.TryGetValue(InterceptorsPropertyName, out existing))
{
registration.Metadata[InterceptorsPropertyName] =
((IEnumerable<Service>)existing).Concat(interceptorServices).Distinct();
}
else
{
registration.Metadata.Add(InterceptorsPropertyName, interceptorServices);
}
}
}
, . : var builder = new ContainerBuilder();
builder.RegisterType<Implementation>()
.As<IInterface>()
.EnableInterfaceInterceptors();
builder.RegisterModule<InterceptorModule>();
var container = builder.Build();
...
var impl = container.Resolve<IInterface>();
impl.DoWork();
, , :
Calling method DoWork with parameters ...
Implementation doing work.
Done: result was .
( , /void, !)
EnableInterfaceInterceptors... EnableInterfaceInterceptors EnableClassInterceptors DynamicProxy2 . , . , , " ", .
- GitHub. , , " " , EnableInterfaceInterceptors . .