1

을 DynamicProxy 인터셉터를 사용하여 나는 다음과 같은 코드가 있습니다는 StructureMap에 종속 레지스트리

_container = new Container(x => x.AddRegistry<ManagerRegistry>()); 

-

public class ManagerRegistry : Registry 
{ 
    public ManagerRegistry() 
    { 
     var proxyGenerator = new ProxyGenerator(); 

     For<IPersonManager>() 
      .EnrichAllWith(t => proxyGenerator.CreateInterfaceProxyWithTarget(
           t, new AuthenticationInterceptor())) 
      .Use<PersonManager>(); 
    } 
} 

-

public class AuthenticationInterceptor : IInterceptor 
{ 
    public void Intercept(IInvocation invocation) 
    { 
     if (!HttpContext.Current.User.IsInRole("Monkey")) 
      throw new Exception("Only monkeys allowed!"); 

     invocation.Proceed(); 
    } 
} 

그것은 interceps의 생성을 StructureMap의 종속성 10, 입니다. 은 DynamicProxy을 사용합니다.
인터셉터에는
종속성이 없으므로 이제는 정상적으로 작동합니다. 다음

그러나 주어진 :

내가 StructureMap에서 그것에 대해 배선을 갈 것 어떻게
public class LoggingInterceptor : IInterceptor 
{ 
    public LoggingInterceptor(ILogger logger) 
    { 

?

답변

1

이 내가 생각 해낸 것입니다.

0

나는 여기에서 완전히 틀릴 수있다, 그러나 이것은 마술을하지 않는가?

public static class ContainerExtensions 
{ 
    public static void RegisterInterceptor<TDependency, TInterceptor>(this IContainer container) 
     where TDependency : class 
     where TInterceptor : IInterceptor 
    { 
     IInterceptor interceptor = container.GetInstance<TInterceptor>(); 

     if (interceptor == null) 
      throw new NullReferenceException("interceptor"); 

     TypeInterceptor typeInterceptor 
      = new GenericTypeInterceptor<TDependency>(interceptor); 

     container.Configure(c => c.RegisterInterceptor(typeInterceptor)); 
    } 
} 

- -

public class GenericTypeInterceptor<TDependency> : TypeInterceptor 
    where TDependency : class 
{ 
    private readonly IInterceptor _interceptor; 
    private readonly ProxyGenerator _proxyGenerator = new ProxyGenerator(); 

    public GenericTypeInterceptor(IInterceptor interceptor) 
    { 
     if (interceptor == null) 
      throw new ArgumentNullException("interceptor"); 

     _interceptor = interceptor; 
    } 

    public object Process(object target, IContext context) 
    { 
     return _proxyGenerator.CreateInterfaceProxyWithTarget(target as TDependency, _interceptor); 
    } 

    public bool MatchesType(Type type) 
    { 
     return typeof(TDependency).IsAssignableFrom(type); 
    } 
} 

나는 결과에 매우 행복 해요

_container.RegisterInterceptor<IPersonManager, LoggingInterceptor>(); 

:

For<IPersonManager>() 
    .EnrichAllWith(t => proxyGenerator.CreateInterfaceProxyWithTarget(
     t, _container.GetInstance<AuthenticationInterceptor>())) 
    .Use<PersonManager>(); 
+0

레지스트리의 컨테이너에 대한 참조가 없습니다. 그렇게하면 RRR 패턴도 위반하게됩니다. – David

+0

아 .. 알았어. 어쨌든 실제로 레지스트리가 필요합니까? 구조체 맵을 사용하여 인스턴스를 릴리즈 할 필요가 없으므로 RRR이 없으므로 RR 만 :-) – Steven