ASP.Net MVC Controller injection - c#

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.

Related

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.

Linq to sql with repository for medium size web application

Is creating a Repository pattern implementation on top of Linq to Sql a good design for a medium size public faced web application?
The app only deals with Sql sever backend and it requires rapid development
I really like LINQ2SQL since it's a neat DAL. I thought of EF but it's too much for this project.
Many thanks in advance for the suggestions.
A large tenet of DDD, from which repository pattern originates, is to create an application which can evolve "easily" over its lifespan. In the future, you may find that Linq2Sql is inadequate for your needs, or (more likely) that the technology was retired (as Linq2Sql would be in favor of EF), etc. Using the repository pattern means you are writing application code against a solid, well-known concept, in an abstract fashion. The actual implementation is hidden from your various application features, meaning you can swap them out in the future as needed.
There are other benefits, too, like allowing a component that uses a repository to be used independently of its environment. Say you have a component that uses a repository, and then you find that you need to be able to use this component in a service to do nightly jobs. You could create a service that uses the same code, but uses an implementation of repository that interacts with a web service, rather than the database. You wrote the code once, just flipped some switches.
Another big reason is unit testing. You don't need to unit test that your ORM or persistence API works, you need to unit test that your application that would otherwise interact with persistence works as expected.
So yeah, I think it's good design.
Answering your question given in the comments: What would such a repository gain you? L2S already is a "repository". The answer is likely to be no.
How many times do people swap their OR mapper? It never happens. And if it does (which is very unlikely), you need to review and retest the whole app anyway. Abstracting the ORM is guarding against an extremely unlikely cost by always paying a very high price. Not a good trade.
Use EF rather, v4.1 and upwards, and skip repository pattern - You are always accessing a db and always accessing ms SQL.

How to properly separate concerns in my architecture without designing a spacecraft?

In my last question I posted some sample code on how I was trying to achieve separation of concerns. I received some ok advice, but I still just don't "get it" and can't figure out how to design my app to properly separate concerns without designing the next space shuttle.
The site I am working on (slowly converting from old ASP section by section) is moderately sized with several different sections including a store (with ~100 orders per day) and gets a decent amount of traffic (~300k uniques/month). I am the primary developer and there might be at most 2-3 devs that will also work on the system.
With this in mind, I am not sure I need full enterprise level architecture (correct me if i am wrong), but since I will be working on this code for the next few years, I want it to perform well and also be easy to extend as needed. I am learning C# and trying to incorporate best practices from the beginning. The old ASP site was a spaghetti mess and I want to avoid that this time around.
My current stab at doing this ended up being a bunch of DTOs with services that validate and make calls to a DAL layer to persist. It was not intentional, but I think the way it is setup now is a perfect anemic domain model. I have been trying to combat this by turning my BLL to domain objects and only use the DTOs to transfer data between the DAL and BO, but it is just not working. I also had all my dtos/blls split up according to the database tables / functionality (eg - YouTube style app - I have separate DTO/BLL/DAL for segments, videos, files, comments, etc).
From what I have been reading, I need to be at least using repositories and probably interfaces as well. This is great, but I am unsure how to move forward. Please help!
From what I can see you have four points that need addressing:
(1) "With this in mind, I am not sure I need full enterprise level architecture"
Lets deal with the high level fluff first. It depends on what you mean by "full enterprise level architecture", but the short answer is "Yes" you need to address many aspects of the system (and it will depend on the context of the system as to what the main ones are). If nothing else, the keys ones would be Change and Supportability. You need to structure the application in a way that supports changes in the future (logical and physical separation of concerns (Dependency Injection is a great for the latter); modular design, etc).
(2) "How to properly separate concerns in my architecture without designing a spacecraft?"
I like this approach (it's an article I wrote that distilled everything I had learnt up to that point) - but here's the gist:
Looking at this you'll have a minimum of six assemblies - and that's not huge. If you can break your system down (separate concerns) into these large buckets it should go a long way to giving what you need.
(3) Detail
Separating concerns into different layers and classes is great but you need to go further than that if you want to be able to effectively deal with change. Dependency Inversion (DI) is a key tool to use here. When I learnt DI it was a hand-rolled affair (as shown in the previous link) but there are lots of frameworks (etc) for it now. If you're new to DI (and you work in .Net) the article will step you through the basics.
(4) How to move forward
Get a simple vertical slice (UI all the way to the DB) working using DI, etc. As you do this you'll also be building the bones of the framework (sub-systems and major plumbing) that your system will use.
Having got that working start on a second slice; it's at this point that you should uncover any places where you're inadvertently not reusing things you should be - this is the time to change those before you build slices 3,4 and 5 - before there's too much rework.
Updates for Comments:
Do you you think I should completely
drop web forms and take up MVC from
scratch or just with what I know for
now?
I have no idea, but for the answer to be 'yes' you'd need to be able to answer these following questions with 'yes':
We have the required skills and experience to use and support MVC.
We have time to make the change (there is clear benefit in making this change).
We know MVC is better suited for our needs.
Making this change does not put successful delivery at risk.
...do I need to move to projects and
setup each of these layers as a
separate project?
Yes. Projects map 1-to-1 with assemblies, so get the benefits of loose-coupling you'll definitely want to separate things that way, and be careful how you set references.
when you refer to POCOs, are you meaning just DTOs or rich domain objects?
DTO not Rich Domain Object. BUT, people seem yo use the terms POCO and DTO interchangeably when strictly speaking they aren't - if you're from the Martin Fowler school of thought. In his view a DTO would be a bunch of POCO's (or other objects(?)) parcelled together for sending "across the wire" so that you only make one call to some external system and not lots of calls.
Everyone says I should not expose my
data structures to my UI, but I say
why not?
Managing dependencies. What you don't want is for you UI to reference the physical data structure because as soon as that changes (and it will) you'll be (to use the technical term) screwed. This is the whole point of layering. What you want to do is have the UI depend on abstractions - not implementations. In the 5-Layer Architecture the POCOs are safe to use for that because they are an abstract / logical definition of 'some thing' (a business concept) and so they should only change if there is a business reason - so in that sense they are fairly stable and safer to depend on.
If you are in the process of rewriting your eCommerce site, you should atleast consider replacing it with a standard package.
There are many more such packages available today. So although the decision to build the original site may have been correct, it is possible that building a custom app is no longer the correct decision.
There are several eConmmerce platforms listed here: Good e-commerce platform for Java or .NET
It should cost much less than the wages of 2-3 developers.

.Net Logger (Write your own vs log4net/enterprise logger/nlog etc.)

I work for an IT department with about 50+ developers. It used to be about 100+ developers but was cut because of the recession.
When our department was bigger there was an ambitious effort made to set up a special architecture group.
One thing this group decided to do was create our own internal logger. They thought it was such a simple task that we could spend recources and do it ourselves. Now we are having issues with performance and difficulty viewing the logs generated and some employees are frustrated that we are spending recources on infrastructure stuff like this instead of focusing on serving our business and using stuff that already exists like log4net or Enterprise Logger.
Can you assist me in listing up reasons why you should not create your own .net logger.
Also reasons for why you should are welcome to get a fair point of view :)
In my last job, almost all the infrastructure was written by us instead of using some of-the-shelf products. (and by "all the infrastructure" I mean ALL of it - Logging, Messaging, Database, Containers of so on).
One of the biggest disadvantages of it was that it made us spend most of our time working on the things that are irrelevant to the end-user instead of adding more features.
from that job I've learned to always focus on the things your product was meant to solve. is your company developing loggers? will the quality of your logger influence your customer more than another feature? I don't think so.
You have a limited budget and manpower - use it wisely. Don't reinvent the wheel. I'm sure that your company and your customers will benefit if you'll focus your attention on things that they need.
in my current project I'm using NHibernate as ORM framework instead of an in-house one that is in use in other projects. instead of fixing bugs in the old ORM framework, my focus is on the main roadmap of the project. furthermore, NHibernate has it's own roadmap which means that additional features will come without much resources from my company.
I would take a different approach. How about first introducing a common interface to your own library such as Common Infrastructure Libraries (http://netcommon.sourceforge.net/). Then you can gradually move all projects over to that interface and if your own library is not up to the job for large projects then simply switch over to one of the open source frameworks (or even a commercial solution).
HTH
Alex
I use a custom logging API that uses a provider model design, that allows an external logging framework to be plugged in. I have developed providers for Log4Net, EntLib and the System.Diagnostics.Trace loggers.
This is essentially the same concept as the Common Infrastructure Libraries.
This means that internal developments do not have an explicit dependency on an external logging framework, yet you can still benefit from all the features of your favorite logging framework. In practice we usually use Log4Net except for customers who are already using EntLib.
It cost money.
It was done so many time before.
You are not as special as you think. If you are, then do something about it.
Maybe you are not as smart as you think.
Are you over staffed? Yet?
I disagree with those who see people reinventing wheels everywhere. A wheel could be a database server, an operating system or a programming language. However things like a ORM framework or this log4net thing aren't in the market enough time to be considered wheels.
Many of these products have a short life cycle, they are replaced by new approaches, just consider how many ORM frameworks have you seen, and then comes Microsoft and launches LINQ.
Logging is not a solid discipline you can learn and it is very platform dependent.
So considering using a logging framework which could come obsolete (log4net vs nlog), wasting your time learning it, does not exclude the option of build your own logging.
I have done this with ORM mapping, for me has been better building a few ORM classes than learning nHybernate.
I wrote my own one because I thought (A) it is based on a TraceListener which is a standard .NET class and (B) it is little and simple to use and maybe because I wanted to write one anyway.
But now I am using NLog in my new projects and replacing it in some old ones!
Am I wrong? Both works for me fine and the reason for using NLog for me was that I wanted a feature that needed an almost rewriting of my custom TraceListener. It turned out a 1 or 2 hour tutorial with a sample app was cheaper for me. This is not a universal situation; but helps with having a more clear image about logging problems.
if your logging solution has such special requirements that an off the shelf solution doesn't work, than maybe making a custom version might be worthwhile.
If this is the argument though, one could also consider downloading an opensource framework and try to customize it.

Inversion of Control with .net

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! :)

Categories