开发者

ASP.NET MVC + WIndsor + Log4Net how to intercept models?

开发者 https://www.devze.com 2023-04-01 21:52 出处:网络
I have follow an excellent tutorial about how to use Windsor and Lo开发者_如何学JAVAg4Net as AOP in ASP.NET MVC

I have follow an excellent tutorial about how to use Windsor and Lo开发者_如何学JAVAg4Net as AOP in ASP.NET MVC

http://cangencer.wordpress.com/2011/06/02/asp-net-mvc-3-aspect-oriented-programming-with-castle-interceptors/

The article show me how to write log for every controller's action without touching any controllers The article also state that I could do so with methods in models but didn't say how.

Can you please help me


I am the author of the link in the question, so first thanks for the kind words. Now onto your question:

It is a lot more difficult and/or impractical to use Interceptors on your models, because for Interceptors to work, you should only be accessing instances of your models through the Castle Container. See the problem?

Let's say that you have a model object called Book and you want to intercept all calls on it, you need to make sure that you never use something like new Book() and only access instances of Book through Castle. Interceptors works by proxying and would not work when you create instances of the objects yourself. This means to able to use interceptors effectively, you would need to structure your whole application around this, which I think might not be the best idea. i.e. everytime you want an instance of Book you need to ask Castle for it instead by using Container.Resolve<Book>(). I personally don't find this approach very elegant. I think it breaks encapsulation and principles of good OO design.

Interception is easy to do with controllers because all controllers are only initialized in once place, the ControllerFactory which is where we hook into. Model objects however can be initialized in different ways as they should indeed be describing your domain model.

There might be a few ways to go around this however. The first one I can think of is to use an ORM such as NHibernate which already uses interceptors in the background that you can hook into for various events such as Save, Update, or any of the method calls. Limitation will be that the interceptors will only work on models retrieved from the database.

Another option is to use a compile time rewriter such as Postsharp which will give you the means to rewrite the code after compilation. This way it is possible to add and remove additional calls to the beginning and end of each method you mark with certain attributes.


You could write Interceptors for your model exactly the same way as the Log4Net Interceptor is done. Only use as ctor argument a contract of your model.

public ControllerModelInterceptor(IModel model)
{
  this.model = model;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消