Inversion of Control with .net - c#

It's rare that I hear someone using Inversion of Control (Ioc) principle with .Net. I have some friends that work with Java that use a lot more Ioc with Spring and PicoContainer.
I understand the principle of removing dependencies from your code... but I have a doubt that it's so much better.
Why do .Net programmers not use (or use less) those types of frameworks? If you do, do you really find a positive effect in the long term?

Lots of people use IOC in .NET, and there are several frameworks available to assist with using IoC. You may see it less in the WinForms side of things, because it's harder to just let the container wire everything together when you are designing forms in Visual Studio, but I can say that for server-side .NET applications, where I work at least, IoC is used very successfully.
Why use it in .NET? For the same reason you use it everywhere else. The 2 biggest things I like are:
Designing for IoC tends to enforce good coding practice - designing to interfaces, low coupling, high cohesion. This also leads to classes that are very easy to unit-test.
System configuration can often be changed without recompiling.
Some other posts discussing the different IoC/DI frameworks available for .NET:
Which C#/.net Dependency Injection frameworks are worth looking into?
Which Dependency Injection Tool Should I Use?

I use StructureMap for dependency injection and have only recently started using it with iBATIS.NET to inject our domain object mappers at runtime (and not through an XML config file, no thanks!).
I've seen immediate benefits. Creating interfaces for all our mappers (such as IPersonMapper) and then adding Moq allows me to write some pretty great database-free unit tests quickly and easily.
Previously (.NET 1.0) I wrote my own plugin system mainly to learn about reflection. Since that time I've implemented some sort of IoC in my projects. Its only recently I started using IoC for making unit tests so much less painful to write. I couldn't imagine doing it any other way at this point.

IoC is not really that commonplace in .Net up until now. And it has everything to do with Microsoft and there promotion campaigns they did. up until now they were more emphasizing the RAD capabilities of VS and in the meanwhile the forgot to promote things like IoC and Di but now they have their own framework called Unity and with the work they did on ASP.Net MVC.
So I guess the majority of people will start to use things like that. Because know they have a MS alternative to use.
And I use StructureMap.

It's getting more common. My current project uses Spring, and on my previous project we used Castle Windsor.
Now I'd like to use the 'convention over configuration' idea, to prevent all those complex XML declarations.

There are a lot theories related to the use of IoC .NET. I think there are a fair amount of developers that don't have the experience in the area. They didn't come from a Java background. They came from a classic ASP, and a VB6 background. Also, Microsoft didn't really promote the use of IoC up until recently.
Further, using IoC assumes several things. First, you must understand what it's used for and what you're getting out of it. Secondly, you must develop your code so that an IoC container can actually be used.
IoC is more than just using another item in the toolbox. It's about knowing how to use, knowing when to use it and maturing as a developer.
As it relates to .NET, I've several IoC containers. I've used Windsor, StructureMap, Unity and, most recently, Ninject. Keep in mind, though, I haven't used all of them in real applications. I like to play around and see what's going on out there. I've found that the market for IoC containers .NET is quite good.

I use it to allow my Unit tests to substitute Mock Classes (simulating actual production classes) for upstream dependant objects so that my unit tests truly only execute and test the code in the one class.method they are written to test.

Try LinFu.IOC 2.0:
http://www.codeproject.com/KB/cs/LinFu_IOC.aspx
It's one of the most flexible IOC containers out there, and like Ninject, there's no XML file to maintain. Unlike Ninject, however, LinFu doesn't force you to write any binding code to wire up your dependencies together. Take a look! :)

Related

DI/CI Dependency/Constructor injection, how do you know what objects are available?

When writing code (C#, Visual Studio 2019), is there any way to tell what the currently available injection options are for your constructor? Intellisense seems unable to help, I usually find myself stumbling across examples to figure out what I can ask for, but there must be a better way to see what objects are provided?
There are a lot of DI implementations out there and I would imagine that some of them have tried to improve things in this area, but in the general case, there is not a way to do this.
This problem is widely considered one of the primary drawbacks of dependency injection - the level of indirection and the fact that things aren't wired up until runtime can make it very hard to understand what classes are used and what code actually gets executed when the program runs.
Try to become as familiar as possible with the composition root of your application, and use the debugger liberally to figure out how things are wired up at runtime.

Adding Ninject to Legacy Project C#

I have just inherited a legacy C# & VB.Net project which I will have to maintain and augment from now how.
There are no interfaces and obviously no Dependency Injection.
The first thing I am thinking of doing is creating interfaces and adding NInject, which would then make it possible to unit test the project eventually.
Is it a good idea or should I leave it alone ?
What are the best practices for implementing DI when it comes to legacy projects.
Thanks
I don't think there's a set best practice, other than use common sense - it's kind of a case by case scenario. A few important questions to ask yourself:
How much effort is going to be required to create interfaces for the current classes?
How much additional effort is going to be required to write proper
unit tests? Will these unit tests add more value than the time spent?
How long is this legacy system even going to be maintained? There's
nothing worse than doing a huge upgrade (requiring testing not only
by the development staff, but by the product user) to replace it in
18 months.
Also, how long has this legacy system been in place
without issue? There's no reason to invent work if it appears stable
and really has low maintenance.

what is the purpose of Binsor when there are c# APIs for Windsor?

I am fairly new to Windsor, and completely new to Binsor, and Boo. However, I am not new to IoC containers.
I have already done several non-trivial things with Windsor. It has all been done in C#, and the XML configuration file syntax is totally foreign to me.
I just recently moved over to a project using Binsor and Boo. I'm having a hard time seeing any additional benefit from using Binsor over the C# APIs provided by Windsor. Does Binsor offer other capabilities that the Windsor C# API does not? Or, is it just so you can configure Windsor using Boo because you like to use Boo?
Some info on Binsor's advantages, particularly in comparison to XML:
http://ayende.com/blog/1687/introducting-binsor-the-boo-dsl-for-windsor
http://ayende.com/blog/2898/binsor-2-0
Maybe DSL is taking it a bit too much, though. It is a single class that has some fancy sticks in it, and a lot of Boo magic
Looking at the age of those posts, Binsor doesn't seem to be the newest project on the block. I assume that some of the techniques in Binsor (if introduced there) have since been applied to the Windsor Fluent Registration API as well:
http://docs.castleproject.org/Default.aspx?Page=Fluent-Registration-API&NS=Windsor
I would assume by default that since Boo is a less popular language that the Binsor API is less frequently updated.
I suggest checking into whether Binsor is still updated. If it isn't, I'd ditch it in favor of the general .Net API. If it is still updated, I'd take a good look at both options. Binsor has a potential to have better Boo support, since the Fluent Registration API was designed with C# as the top priority.
Disclaimer: I am not directly involved with the Castle.Windsor or Binsor projects, and I have only skimmed the Boo documentation a few times out of curiosity. Most of this info I've gathered from some minor Windsor experience (with the Fluent Registration API) and from Google - I'm making a lot of assumptions.

ASP.Net MVC Controller injection

I am looking for suggestions on good ways to design a new ASP.NET Mvc project. It is of medium size and is relatively simple in structure. I had initially used Spring.Net to wire my service objects into the correct constructors but now management has told me that Spring.Net or any other IOC container is not to be use in our environment.
I am having a bit of trouble figuring out a good way to set this up without DI. I would like to be able to assign service implementations to controllers in a way that allows for a low amount of coupling between controllers and services and to limit, as much as possible, the dependably of controllers on individual service implementations. I guess my question boils down to that fact that I am unsure of where I should manually wire up my application in the MVC model.
Any suggestions?
Since you are using ASP.NET MVC 3 you could write a custom dependency resolver. You will of course still design your controllers taking interfaces in their constructors in order to weaken the coupling between the layers. And then in the custom dependency resolver, in order to satisfy the ridiculous requirement that was imposed to you, you will have to manually say that when you have an ISomeService you return an instance of SomeServiceImpl. You know, the kind of things that object containers and DI frameworks already do for you. So you will basically have to reinvent some wheels. By the way Ayende blogged about how you could build a custom IoC container in 15 lines of code but of course that's not a reason that you should ever do anything like this.
People imposing such requirements should face a trial and be sentenced to never ever have to approach an application design. Imposing such requirement illustrates some total lack of knowledge about good practices in designing applications. Those people should be advised before they bring further damage to the company.
So simply explain those people that by reinventing wheels there are 2 mistakes:
you will waste a lot of time for something that was already done by someone else
you will make errors as you will not take into considerations all the edge cases that were taken into account by someone else designing a reusable DI framework.
At the end of the day you will ship your application late on schedule (as you would have wasted time to write plumbing code) and even worse you will ship an application that will contain potential bugs.
Conclusion: expensive and buggy product. Your management must have really has lost its mind :-)
Conclusion2: use an existing DI framework. Management won't even notice as they don't seem to understand the technical aspects of an application by imposing such requirements.
First of all, I would question why management has mandated that you can't use a pattern and tools that would allow you to achieve loose coupling and dependency injection. Is this something that can be discussed and reasoned about?
With an IoC container, it is trivial to implement an IControllerFactory that resolves controllers from the container and injects the necessary services.
In MVC 3, there is IDependencyResolver which you could use to achieve slightly looser coupling (via a Service Locator pattern/anti-pattern) than instantiating services directly inside controllers; this interface was designed to be used with an IoC container though really and would be a poorer substitute on its own.
Does your boss have pointy hair? http://www.dilbert.com/
You could save yourself some time by using http://unitymvc3.codeplex.com/ rather than writing your own custom dependency resolver. It's downloadable via Nuget http://nuget.org/. If you use an IOC container such as this, and use constructor injection, you will find your unit tests are much easier to write. That's assuming your manager believes in unit testing ;-) Good luck!
management has told me that Spring.Net or any other IOC container is
not to be use in our environment.
Management is telling you that you are not allowed to write loose coupled, testable and higly maintainable applications, that’s what they are telling you. That’s an odd restriction.
Dependency injection is an advanced technology that many developers don't understand. However, management will never understand it, and it is not their job to understand it. They may dictate the type of technology (.NET vs. Java for instance), because this impacts the kinds of personnel they need to hire, but when they start dictating on low level implementation details that prevent you from writing descent software, your company is heading for disaster.
Leave that company now you can!
Your other option is using the source code of the Simple Injector. The code base is small enough (about 500 lines, just use the SimpleInjector.NET project) to be able to copy it to a local project (and the license permits it). This way it’s your own local DI container, but fully tested :-)
Good luck.
You need a new home. There are plenty of organizations looking for talented engineers who care about quality and scalable architectures. Make sure you find the right one and they will be glad to find you.
Avoid the temptation to save your current team from their own short-sightedness. From your descriptions, it sounds like you are already a pariah despite your talents. Accept the fact that you won't be listened to.
The best strategy is to fake being a born-again team player. Build your MVC project exactly the way your boss has asked, i.e. the dumb way, with no separation of concerns. When version 1 of your project is finish and passes QA (if you have any QA), your boss will probably think he is vindicated. Be prepared for this reaction.
The best hope you have of enlightening your current team members is to show them that even if you build software using the same dumb practices they are comfortable with, you can still run rings around them. This can be fun. Then, when you leave, you give them a chance to reflect on the possibility that you were on to something. They can either take that chance or opt for continued comfort, but it won't be your problem any longer.

IoC/DI frameworks with Smart Client Winform apps: How should I approach this?

I'm starting a new Winforms app, and I intend to use an IoC/DI framework (probably Ninject, but I'm also thinking about StructureMap and LinFu).
It seems like nearly everyone who is using IoC/DI is doing so in a web based environment and have found virtually nothing on using Winforms with it.
I'd like to know if anyone is using IoC/DI with Winforms and what approaches you used to deal with Winforms related issues (for instance, how do you make the container available in various parts of the app, do you use the framework to instantiate your forms, etc..)
If anyone knows of any open source Winforms based projects that use IoC/DI (doesn't matter which framework, I should be able to translate concepts) I would like links to those as well.
EDIT:
Are people just not writing Smart Clients anymore?
EDIT:
If you could point me to some real-world code that uses IoC/DI in a Winforms or even console type application (ie, something that is not Web based) I'd appreciate it.
EDIT:
I've been using Ninject and discovered that Ninject will happily inject an instance of it's common kernel interface if you specify an IKernel constructor parameter. This has been working out pretty well, but I'd still like to hear other approaches people use.
The Microsoft patterns and practices team which maintains the Unity injection container also created the Smart Client - Composite UI Application Block for winforms, which I believe uses Unity. I know the new WPF version called Composite Client Application Guidance (codename Prism) uses Unity
I just recently started writing a new WinForms application from scratch using StructureMap for IoC. I've previously looked at SCSF and CAB, but found those overly complex.
I wrote some fluent APIs on top of StructureMaps registry so our modules can register commands, presenters and views.
From my experience it has been worth the effort in all regards, I would never want to write a WinForms app without using these tools and the highly structured modular approach again.
I've written an application for displaying maps from OpenStreetMap vector data (http://wiki.openstreetmap.org/index.php/Kosmos). I developed my own simple MVP framework which uses Windsor Castle as an IoC container. You can download the source code if you're interested, it's currently BSD-licensed.
Right now I'm (slowly) working on a redesign of this framework to be able to generate forms dynamically (instead of using the visual designer). I'm toying with the idea of introducing some kind of a fluent interface for building forms and controls, but I haven't yet come up with an elegant solution for this.
If you just want an Inversion of Control container and want to get a little lower level than Unity, check out ObjectBuilder from the Microsoft Patterns and Practices group. Unity is an abstraction layer on top of ObjectBuilder.

Categories