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

I have follow an excellent tutorial about how to use Windsor and Log4Net 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;
}

Related

In IoC, what is the practice for loading an object by ID?

I've just started learning about IoC, and I understand the general use of it, but so far, the loading process from AutoFac, Ninject and Zenject seem to be based on loading an object not based on data.
In other words, ConsoleLogger is created when ILogger is requested, which does not require any special ID's, and that makes sense. However, what about when I want to load IUser for Id 4? Is there a standard IoC for handling that, or are the interfaces supposed to carry methods for loading based on Id?
For instance, am I supposed to have IUserManager, with LoadUser(int id) as a method? or is there some IoC structure for this as well?
Thanks.
[note: I did search the web for this, but my queries did not seem to pull up relevant information and the similar question search yields too many generic questions to filter]
IoC containers rules the way we link object's by dependencies, dependencies means some logic under Iterfaces, so IoC mostly works on Type level rather then Instance level.
Please note that types which has no any dependencies, interfaces as well as special scope requirements may be legally created by using "new" keyword for e.g. Data Transfer Objects (dto's).
In your case, you probably need a some kind of factory that can realize by parameters what kind of object caller is needed.
However, I'll suggest to you separate data from business logic as much is it can be separated.

What are the benefits of using Dependency Injection when retrieving implementations of an interface at runtime?

public List<IBusinessObject> RetrieveAllBusinessObjects()
{
var businessObjectType= typeof(IBusinessObject);
List<Type> implementationsOfBusinessObject = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(s => s.GetTypes())
.Where(businessObjectType.IsAssignableFrom).ToList();
return implementationsOfBusinessObject.Select(t =>(IBusinessObject)Activator.CreateInstance(t)).ToList();
}
I was suggested by a user on stack overflow that I should check out dependency injection as a workaround for the above snippit. What would be the benefits of this?
Just a little overview on what the scenario is:
Our database has little to no store procedures so we have begun implementing C# business objects for our more complicated tables. As we are hoping to switch databases some time soon this seems to be the best option. All of the business objects must be loaded using reflection at runtime to help manage them. All of these business objects implement the interface IBusinessObject.
The suggestion to use dependency injection came from this question
EDIT:
The RetrieveAllBusinessObjects method is in a class behind an interface so is directly testable
We use AutoFac if that changes anything. We don't use a separate config file.
-
instead of using the code above, you simply use DI which is configured in the config file of the app but also sometimes you can decorate a property or a parameter in a method which will then be automatically injected in (by the mapping set up either programmatically or via config) when the request is made to access that object or when it is going to be invoked in the method being called in the params.
it also makes it a bit more testable in that you can create different concrete types which implement of an interface, then instead of having to recompile the code, you just flick the mappings by the config file and viola...all works.
DI would do the above without you having to write code to do it so there's less opportunity for you to introduce bugs.
DI gives you many more benefits such as
Making it easier to test individual units of code. Dependencies can be mocked, so you can limit the code being tested
Easy to understand the dependencies within your code. Dependencies generally get injected in certain places, usually the constructor.
Linked to 1/ above, because you should now defined interfaces between your code, when your requirements change & you need to rewrite a component, you can do so with a higher level confidence that it will work with your existing code-base.
There are other benefits that others can probably describe better, but you'll need to evaluate those according to your needs.

What good is Unity DI in MVC?

I'm slightly new to Unity and IoC, but not to MVC. I've been reading and reading about using Unity with MVC and the only really useful thing I'm consistently seeing is the ability to get free DI with the controllers.
To go from this:
public HomeController() : this(new UserRepository())
{
}
public HomeController(IUserRepository userRepository)
{
this.UserRepository = userRepository;
}
To this:
public HomeController(IUserRepository userRepository)
{
this.UserRepository = userRepository;
}
Basically, allowing me to drop the no parameter constructor. This is great and all and I'm going to implement this for sure, but it doesn't seem like it's anything really that great for all the hype about IoC libraries. Going the way of using Unity as a service locator sounds compelling, but many would argue it's an anti pattern.
So my question is, with service locating out of the question and some DI opportunities with Views and Filters, is there anything else I gain from using Unity? I just want to make sure I'm not missing something wonderful like free DI support for all class constructors.
EDIT:
I understand the testability purpose behind using Unity DI with MVC controllers. But all I would have to do is add that one extra little constructor, nix Unity, and I could UnitTest just the same. Where is the great benefit in registering your repository types and having a custom controller factory when the alternative is simpler? The alternative being native DI. I guess I'm really wondering what is so great about Unity (or any IoC library) besides Service Locating which is bad. Is free Controller DI really the ONLY thing I get from Unity?
A good IoC container not only creates the concrete class for you, it examines the couplings between that type and other types. If there are additional dependencies, it resolves them and creates instances of all of the classes that are required.
You can do fancy things like conditional binding. Here's an example using Ninject (my preferred IoC):
ninjectKernel.Bind<IValueCalculator>().To<LinqValueCalculator>();
ninjectKernel.Bind<IValueCalculator>().To<IterativeValueCalculator().WhenInjectedInto<LimitShoppingCart>();
What ninject is doing here is creating an instance of IterativeValueCalculator when injecting into LimitShoppingCart and an instance of LinqValueCalulator for any other injection.
Greatest benefit is separation of concern (decoupling) and testability.
Regarding why Service Locator is considered bad(by some guys) you can read this blog-post by Mark Seeman.
Answering on your question What is so good in Unity I can say that apart from all the testability, loosely-coupling and other blah-blah-blah-s everyone is talking about you can use such awesome feature like Unity's Interception which allows to do some AOP-like things. I've used it in some of last projects and liked it pretty much. Strongly recommended!
p.s. Seems like Castle Windsor DI container has similar feature as well(called Interceptors). Other containers - not sure.
Besides testing (which is a huge benefit and should not be under estimated), dependency injection allows:
Maintainability: The ability to alter the behavior of your code with a single change.
If you decide to change the class that retrieves your users across all your controllers/services etc. without dependency injection, you need to update each and every constructor plus any other random new instances that are being created, provided you remember where each one lives. DI allows you to change one definition that is then used across all implementations.
Scope: With a single line of code you can alter your implementation to create a singleton, a class that is only created on each new web request or on each new thread
Readability: The use of dependency injection means that all your concrete classes are defined in one place. As a developer coming onto a project, I can quickly and easily see exactly which concrete classes are mapped to which interfaces and know that there are no hidden implemetations. It means I can not only read the code better but empowers me to have the confidence to develop against the code
Design: I believe using dependency injection helps create well designed code. You automatically code to interfaces, your code becomes cleaner because you haven't got strange blocks of code to help you test
And let's no forget...
Testing: Testing is huge! Dependency injection allows you to test your code without having to write code specifically for tests. Ok, you can create a new constructor, but what is stop anyone else using that constructor for a purpose it has not been intended for. What if another developer comes along six months later and adds production logic to your 'test' constructor. Ok, so you can make it internal but this can still be used by production code. Why give them the option.
My experience with IoC frameworks has been largely around Ninject. As such, the above is based on what I know of Ninject, however the same principles should remain the same across other frameworks.
No the main point is that you then have a mapping somewhere that specifies the concrete type of IUserRepository. And the reason that you might like that is that you can then create a UnitTest that specifies a mocked version of IUserRepository and execute your tests without changing anything in your controller.
Testability mostly, but id suggest looking at Ninject, it plays well with MVC. To get the full benefits of IOC you should really be combining this with Moq or a similar mocking framework.
Besides the testability, I think you can also add the extensibility as one of the advantages. One of the best practices of Software Development is "working with abstractions, not with implementations" and, while you can do it in several ways, Unity provides a very extensible and easy way to achieve this. By using this, you will be creating abstractions that will define the contracts that your component must comply. Say that you want to change totally the Repository that your application currently uses. With DI you just "swap" the component without the need of changing a single line of code on your application. If you are using hard references, you might need to change and recompile your application because of a component that is external to it (In a different layer)
So, bottom line, IMHO, using DI helps you to have pluggable components in your application and have a SOLID application design

Remove dependency to logging code

I have more like desing question as I'm refactoring quite big piece of code that I took over.
It's not modular, basically it's pseudo-object-oriented code. It contains hard coded dependencies, no interfaces, multiple responsibilities etc. Just mayhem.
Among others it contains a great deal of internal calls to class called Audit, that contains methods like Log, Info, LogError etc... That class has to be configured in application config in order to work, otherwise it's crash. And that's the main pain for me. And please, let's focus on that issue in responses, namely making client code independent of logging classes/solutions/frameworks.
And now, I would like those classes, that have that Audit class dependency hardcoded, refactored in order to obtain several benefits:
First is to extract them nicely to different assemblies, as I will need some functionality available in other applications (for instance generating attachments code - let's call it AttachmentsGenerator class, that until now was specyfic to one application, but now that code could be used in many places)
Remove internal dependencies so that other application that will take advantage of my AttachmentsGenerator class without the need to add reference to other
Do a magic trick in order to allow AttachmentsGenerator class to report some audit info, traces etc. But I don't want it to have hardcoded implementation. As a matter of fact, I don't want it to be mandatory, so it would be possible to use AttachmentsGenerator without that internal logging configured and without the necessity for the client code to add reference to another assemblies in order to use logging. Bottom line: if client code wants to use AttachmentsGenerator, it adds reference to assembly that contains that class, then it uses new operator and that's all.
What kind approach can I use in terms of design patterns etc to achieve it? I would appreciate some links to articles that address that issue - as it can be timeconsuming to elaborate ideas in answer. Or if you can suggest simple interface/class/assembly sketch.
Thanks a lot,
Paweł
Edit 1: As my question is not quite clear, I'll rephrase it once again: This is my plan, are there other interesting ways to do this?
Seems like the easiest way to do this would be to use dependency injection.
Create a generic ILogger interface with methods for logging.
Create a concrete implementation of ILogger that just does nothing for all the methods (e.g. NullLogger)
Create another concrete implementation that actually does logging via whatever framework you choose (e.g. log4net)
Use a DI tool (spring, structure map, etc.) to inject the appropriate implementation depending on whether or not you want logging enabled.
Implement logging (and any other cross-cutting concerns) as a Decorator. That's way more SOLID than having to inject some ILogger interface into each and every service (which would violate both the Single Responsibility Principle and DRY).

Pattern for objects initialization at startup

I'm building an application and as time goes on, I have more and more objects to initialize at startup. Moveover, some of the newer objects depend on others so I'm getting some kind of spaggetti initialization where objects are created then passed to other constructors. I'm suspecting that I'm getting it wrong.
For example I have a WinForm which accepts a "Controller" class and 2 events. The controller needs to be told about the existence of a DataGridView from the WinForm so it has a method
Controller::SetDataGridReference(DataGridView^ dgv)
Is there a general method of instanciating objects at startup then referencing those objects to each another?
I've been told that putting all the required classes as constructor parameters is a good practice but frankly, I don't see how I can do that here.
I don't really think that the language matters
This looks like a textbook case for using dependency injection (DI). It will certainly help with your spaghetti code and can even assist with unit testing. If you want to make a gradual migration towards DI you might want to consider refactoring the objects with similar relationships and using a few sets of factory classes that can handle all the boilerplate chain intialization as well as centralizing where all that takes place in your code base.
I can recommend Google Guice as a good DI framework for Java. Even if you arent using Java it is a good DI model to compare against other language's DI frameworks
Two patterns pop into mind as possibly appropriate depending on the specifics of your problem:
Abstract Factory Pattern. This can work with or without the Dependency Injection approach suggested by #Scanningcrew.
Mediator Pattern. Construct a mediator. Pass the mediator into the constructor of each object. Have each object register with the mediator. Then the objects don't need to know about each other explicitly. This works well when you have a set number of objects interacting with each other.
Use the Controller Design Pattern.
That is, create a SINGLE class that will be instanced on program initialization, called Controller. On the constructor of that class, create all other objects. Whatever object that needs any other objects should receive said object as a parameter on its constructor. No one, no absolutely any other object should create anything on their constructor. Pass everything as parameters on their constructors. Also, on the Controller class destructor/dispose call all objects destructor/dispose method in reverse order. This won't reduce your code, but it will make if far better to understand and debug later on.
Dependency Injection should help here: at application boot you can choice to build the complete (or sort of) graph of objects. The entry point of your application will instantiate the DI container of your choice, the you just request the root object.
For example Google Guice comes with a very nice Object grapher.
For the objects interaction, I would go for a Mediator. Check out this definition:
"Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently."
For the instantiation, I would consider the Dependency Injection. Remember that you can freely use and mix design patterns to achieve your goals.

Categories

Resources