IoC-Like-Codegeneration (T4?) - c#

This request might sounds a little bit odd, but application-performance and maintenance is cruciual, so I'm really looking for something as described.
Because I'm not sure if the 3 words are enough to explain what I'm looking for, here's an example:
I use IoC a lot, especially if I have dyniamical behaviours, which is often the case.
It's a very easy and frankly cool technique to have a loose coupled application.
But the freedom comes with a price of a higher performance-cost, compared with a "hard wired" solution.
Normally this is not a too big issue, but in the current case, it is.
So what I'd like to have is a feature which works like an IoC, but of course with a hard-wired .cs-file, instead of an "generated at runtime" Container.
Like if I need all implementations of IBehaviour, I'd get an output such as "behaviours = new List { impl1, impl2, ... }, instead of behaviours = Container.GetAllInstancesOf()
Hope it's clear what I'm looking for and that something like this exists.
And if not: What would be the way to implement this feature? Only way I can imagine is a VisualStudio-Plugin which reflects a compiled dll and with the help of custom attributes can write a .t4-file.
Cheers!

I don't know if what you're looking for exists, but I implemented something which may serve as an example to get you started: a T4 typed factory generator. Basically you mark your class with an attribute and T4 will generate a factory implementation based on a factory interface (if it doesn't exist, the script will generate the factory interface as well).
You can look at the code at https://github.com/PombeirP/T4Factories, and a NuGet package is available at https://www.nuget.org/packages/T4Factories/.
Hope this helps.

Are you sure that ioc has:
higher performance-cost, compared with a "hard wired" solution
?
Comparing the performance, you can see that:
singleton registration takes 68ms, without container 78ms
transient (a new instance is created every time) takes 66ms, without container 88ms
Moreover, now IoC container is very small, for example DryIoc has no more than 2500 lines of code including comments.

Update:
DryIocZero supports compile-time generation of factories with all registered dependencies (I am a maintainer).

I'm currently working on a compile time IOC container for .Net which should have almost zero overhead (for many cases it generates practically the same code as you would write yourself). Try it out at https://github.com/YairHalberstadt/stronginject.

Related

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

Problem implementing Interceptor pattern

I'm attempting to develop an Interceptor framework (in C#) where I can simply implement some interfaces, and through the use of some static initialization, register all my Interceptors with a common Dispatcher to be invoked at a later time.
The problem lies in the fact that my Interceptor implementations are never actually referenced by my application so the static constructors never get called, and as a result, the Interceptors are never registered.
If possible, I would like to keep all references to my Interceptor libraries out of my application, as this is my way of (hopefully) enforcing loose coupling across different modules.
Hopefully this makes some sense. Let me know if there's anything I can clarify...
Does anyone have any ideas, or perhaps a better way to go about implementing my Interceptor pattern?
Update: I came across Spring.NET. I've heard of it before, but never really looked into it. It sounds like it has a lot of great features that would be very useful for what I'm trying to do. Does anyone have any experience with Spring.NET?
TIA,
Jeremy
I strongly recommend looking at some of the existing Aspect Oriented Programming (AOP) frameworks for .NET since they will likely accomplish what you're trying to achieve in a more generalized and maintainable fashion. Most of them are open source, so where they don't meet your needs you may be able to extend and contribute to the project(s).
More details: http://www.sharpcrafters.com/aop.net
Spring.NET, Unity Framework and StructureMap are probably your best bet. What I have done in the past is used MVC and created a custom controller factory to generate my controllers. However using dependency injection became difficult with frameworks like NinJect because of it's lack of an XML configuration (Ninject uses a fluent API). The reason it's difficult ofcourse is that you are not sure at runtime what modules you will need dependency injection for.
The three IOC containers above all have some form of XML configuration which can be modified outside of your compilation and therefore help to make your application more modular, so there would be (hopefully) no need for static initialization. The major plus being that you don't have to worry as much about thread safety.

Real world solutions using Dependency Injection

I was reading about DI thoroughly, and it seems interesting. So far, I'm totally living without it.
All the examples i saw are related to JNDI and how DI helps you being more flexible.
What is real life applications/problems that you solved with DI that will be hard to solve in other ways?
UPDATE
All the answers till now are educating, but to rephrase the question, I'm looking for examples in your programming life, that made you say "this problem will be best solved with a DI framework".
Just the other day, I decided to read up on dependency injection. Until then, I only knew the word. Honestly, my reaction to Martin Fowler's article was, "That's it?"
I have to agree with James Shore:
"Dependency Injection" is a 25-dollar term for a 5-cent concept.
That doesn't mean at all that it's a bad concept. But seriously, when an instance A needs to work with another instance B, it comes down to these choices:
let A find B:
That means B must be global. Evil.
let A create B:
Fine, if only A needs B. As soon as C also needs B, replace A by C in this list. Note that a test case would be a C, so if you do want to test, this choice is gone as well.
give B to A:
That's dependency injection.
Am I missing something? (Note that I'm from the Python world, so maybe there are language specific points I'm not seeing.)
Yesterday I found a mobile on the bus. The person who lost it had no clue about the person possessing her mobile. I called her dad and told him I have the mobile of his daughter. So I injected the dependency from me into him. Typically a case of the hollywood principle "Don't call us (because you can't!), we call you". Later he came and picked up his daughters phone.
I'd call that a real world problem which I solved by dependency injection, isn't it?
In my opinion, DI is not THE way to solve problems, for which we would not have another solution. Factories can be another way to solve such problems.
So there is no real answer for your question, because DI is just one way besides others. It is just a pretty hip, although very elegant way.
I really enjoyed DI when I had this DAOs, which needed an SQLMapper. I just had to inject the different mappers into the fatherclass once and the rest was done by configuration. Saved me a lot of time and LOCs, but I still can't name this a problem for which there is no other solution.
I use dependency injection for testing all the time. It's also extremely helpful when you have a bunch of large systems that you do not want to directly tie together (extremely loose coupling).
If you're using Java, I would recommend Google Guice, since it rocks so much. For C++, I recommend Qt IOC. For .NET, the Castle Project provides a nice IOC system. There is also a Spring implementation basically everywhere, but that's boring.
DI allows you to create applications that can be configured and reconfigured without touching the codebase itself. Not just urls or settings though; generic objects can be written in code, and then "customized" or configured via XML files to achieve the specific result desired for the given case.
For example, I can create a RegexDetective class where the actual regex it looks for is provided in a setter, and then in my Spring DI XML file, define one actual regex expression for RegexDetective.setRegex() for a deployment of SleuthApp going to London. Then a few days later I can go back and update the regex in the XML file for another deployment of SleuthApp shipping out to Siberia.
DI also allows one to define specific implementations of interfaces in a similar fashion, outside of the codebase in XML, to modify behavior of an application without actually touching the code, such as setting the AngryDetective or ArcticDetective implementation of the Detective interface, in the DI XML file.
We run a multimedia service for different countries. We run the same code for everyone but sometimes, business rules are different from one country to another. In this case, we inject different Spring MVC Interceptor for one client or for another.
Then, in the deploy phase, a script "chooses" which DI file is needed, based on the last letters of the files (fr for France, ch for Switzerland etc...)
application-context.xml-fr
application-context.xml-ch
etc...
That's the only good use I see in DI. I'm not a fan of DI though.
I've used Spring's IoC (DI) container for the last three web apps I've developed. I don't think its suited to one particular type of problem, rather it's a different way of solving a problem. It's as you've said, a more flexible approach to large systems. My personal favourite features of DI are that you can prepare better unit tests because your classes are highly decoupled. Also important for me is code reuse. Since I use the container in many apps, I can use the same components and know that their dependencies will be fed in externally.
In large multi-module applications using DI, a module only depends on the interfaces on the collaborator of its classes, which cuts compile-time dependency graphs.
In the context of frameworks (calling "your" functional code, as opposed to functional code calling a library), this is required. Your code can have compiling dependencies to the framework, but we all know that the framework (out of your hands) could not have compile dependencies to your code ;-)
I use DI primarily for ease of testing. Additionally it fosters the model of stubbing out your service calls to provide isolation and the ability to implement independent of service development.

Unity Best Practices with .NET Framework Classes

I am just getting started using any DI/IoC toolset and have a very basic question. I am using Unity as we will also be using a number of the Enterprise Library blocks throughout the application.
The question that I have is around the dependencies to .NET framework classes. For instance, in one of the classes that I am working on currently, I need to create DirectoryInfo classes. According to my understanding, one of the best practices in DI is to never use the "new" keyword - as this introduces a hard dependency. So how should I get a new DirectoryInfo? Add it as an item to the container and have the container a dependency of the class? This seems that it would be impratical in real life usage as I would end up with the container being configurated with literally hudreds to thousands of framework classes. I would consider that to be a maintance nightmare.
The way I see it, the majority of classes in the BCL (base class library) are utiity classes, and generally don't have a ton of other dependancies other than straight up call graphs.
DI is designed to flatten the call graphs and prevent a lot of cross talk between classes. As such, and the fact that you can't do anything about the BCL chattiness, you might as well just accept them for what they are and go ahead and use new...
The only reason why you wouldn't want to, is for testing purposes. You're not typically testing BCL classes, but you might want to replace a BCL class with a mocked version so that it doesn't actually do whatever it is the class does, only pretend to do so.. and you can use stuff like SystemWrapper to do that if necessary.
I would say that is a little over engineering. I would think that the path of the DirectoryInfo to create should be passed in or have some sort of configuration repository( or service) class passed in that holds (or gives you a way to get) that data.
I wouldn't register low-level classes like DirectoryInfo with the container - it's not really a problem to use new in some places in your application, as long as this requirement doesn't 'leak out' into higher-level classes. So in this example, it probably makes sense to create and use the DirectoryInfo directly in a class, yet have instances of that class be injected into their dependents by the container.
First you can look as SystemWrapper library. It wraps DirectoryInfo object so you can mock it.
Next you can look at tutorial to TDD using Rhino Mocks and SystemWrapper. You can see there usage of DI; however, the example there doesn't use any of IoC.
Hope it helps.

What is the overhead cost associated with IoC containers like StructureMap?

After attending a recent Alt.NET group on IoC, I got to thinking about the tools available and how they might work. StructureMap in particular uses both attributes and bootstrapper concepts to map requests for IThing to ConcreteThing. Attributes automatically throw up flags for me that either reflection or IL injection is going on. Does anyone know exactly how this works (for StructureMap or other IoC tools) and what the associated overhead might be either at run-time or compile-time?
I can't say much for other IoC toolkits but I use Spring.Net and have found that there is a one off initial performance penalty at startup. Once the container has been configured the application runs unaffected.
I use Windsor from the CastleProject and have found it immensely useful in reducing dependencies. I haven't noticed a performance issue yet but one thing I do find is that the configuration can get a bit cumbersome. To help in this regard I'm starting to look at Binsor, which is a DSL for Windsor written in boo.
Another thing to be aware of is that when navigating code you wont be able to go to the code that will be executing at runtime.
They major problem is that code becomes hard to understand. It might become pure magical if one overuse IoC. Another problem is performance. In most cases performance lost is not noticeable. But when you start creating most of your objects via IoC container, it can suddenly drop below ocean level.
I built a very lightweight and basic IOC, here:
http://blogs.microsoft.co.il/blogs/shay/archive/2008/09/30/building-custom-object-mapper.aspx
It's not an alternative to the libraries You mentioned but if all that You need is to resolve a type by giving its interface it might be a perfect solution.
I don't handle instantiation types (singleton, transient, thread, pool...), all object will be instantiated as singletons, you call it like:
IRepository _repository = ObjectFactory.BuildFactory<IRepository>();
Shay

Categories

Resources