Tôi có một NinjectWebCommon như sau. Tôi không thể nhận được TimingInterceptor kích hoạt trên phương thức có thuộc tính "Timing". Nó hoạt động tốt nếu intercetor được định nghĩa ở cấp lớp mà tất cả các cuộc gọi phương thức sẽ bị chặn, nhưng tôi muốn có khả năng xác định phương thức mà tôi muốn chặn (chọn tham gia).cách sử dụng đánh chặn Ninject bằng cách sử dụng InterceptAttribute
Tôi có Ninject.Extensions.Interception.DynamicProxy được thêm vào.
public static class NinjectWebCommon
{
private static readonly Bootstrapper bootstrapper = new Bootstrapper();
/// <summary>
/// Starts the application
/// </summary>
public static void Start()
{
DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
bootstrapper.Initialize(CreateKernel);
}
/// <summary>
/// Stops the application.
/// </summary>
public static void Stop()
{
bootstrapper.ShutDown();
}
/// <summary>
/// Creates the kernel that will manage your application.
/// </summary>
/// <returns>The created kernel.</returns>
private static IKernel CreateKernel()
{
var NinjectSettings = new NinjectSettings();
var kernel = new StandardKernel(NinjectSettings);
kernel.Bind<Func<IKernel>>().ToMethod(ctx =>() => new Bootstrapper().Kernel);
kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
GlobalConfiguration.Configuration.DependencyResolver = new BazingaNinjectResolver(kernel);
RegisterServices(kernel);
return kernel;
}
/// <summary>
/// Load your modules or register your services here!
/// </summary>
/// <param name="kernel">The kernel.</param>
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<IMyService>().To<MyService>().InRequestScope();
}
}
lớp dịch vụ của tôi xác định như sau
public class MyService : IMyService
{
Logger log;
public MyService()
{
log = LogManager.GetLogger(this.GetType().FullName);
}
[Timing]
public string GetString()
{
log.Info("log me!!");
return "Cool string !!!!";
}
public string GetUnInterceptString()
{
return "Not intercepted";
}
}
Interceptor và thuộc tính xác định như sau
public class TimingAttribute : InterceptAttribute
{
public override IInterceptor CreateInterceptor(IProxyRequest request)
{
return request.Context.Kernel.Get<TimingInterceptor>();
}
}
public class TimingInterceptor : SimpleInterceptor
{
readonly Stopwatch _stopwatch = new Stopwatch();
protected override void BeforeInvoke(IInvocation invocation)
{
_stopwatch.Start();
}
protected override void AfterInvoke(IInvocation invocation)
{
_stopwatch.Stop();
string message = string.Format("Execution of {0} took {1}.",
invocation.Request.Method,
_stopwatch.Elapsed);
_stopwatch.Reset();
}
}
đúng, tôi nhớ đã thấy nó được đề cập ở đâu đó, nó hoạt động bây giờ nhờ – Eatdoku
là nó có thể đánh chặn các phương thức riêng bằng cách sử dụng thuộc tính? – Eatdoku
Không phải với ninject, bạn sẽ cần postsharp, hoặc một số khác AOP ma thuật –