Dependency Injection in .NET

Mark Seemann

Mentioned 44

"Dependency Injection in .NET" is a comprehensive guide that introduces DI to .NET developers. It covers core concepts and patterns, and introduces important DI frameworks, such as StructureMap, Windsor, and Spring.NET.

More on Amazon.com

Mentioned in questions and answers.

After reading "Dependency Injection in .NET" by Mark Seemann I stay away from the Service Locator which is an anti-pattern.

Upon reading the release notes on MVC 4 I see:

Improved Inversion of Control (IoC) via DependencyResolver: Web API now uses the service locator pattern implemented by MVC’s dependency resolver to obtain instances for many different facilities.

Thus I'm left curious and confused why Microsoft would use a service locator in 2012.

That's an implementation detail that you shouldn't care about. The important thing is that now that the Web API uses the DependencyResolver to resolve dependencies for many different facilities, you will be able to use a real dependency injection whenever you want to plug into those facilities. So in your code you will be using a real dependency injection. If Microsoft didn't use the DependencyResolver then it would have been you that must have used it (as a service locator anti-pattern) in your code in order to resolve dependencies when you want to implement some custom functionality. This would have been bad for you. Now it's bad for Microsoft but you don't care about them.

Thus I'm left curious and confused why Microsoft would use a service locator in 2012.

Because designing a framework is not the same as designing an application using a framework. There are some different things to take into consideration when designing a reusable framework such as ASP.NET MVC rather than just what's written in the books. Some example is to design the framework in such a way that a person using this framework will be able to take advantage of the best practices written in the books in his code using this framework.

I'm reading his book Dependency Injection in Net.

1) Here he's saying that Bastard Injection occurs only when we use Foreign Default.

But in his book, the illustration on page 148 shows that Bastard Injection occurs when the default implementation of the dependency is either Foreign Default or Local Default:

enter image description here

So does Bastard Injection anti-pattern also occur when default implementation of dependency is a Local Default?

2) Here ( and also in his book ) he notes that it's ok for a class to have an optional dependency, provided that a default implementation of this dependency is a good Local Default:

But in next article he seems to object to having optional dependencies at all, even if the default implementation is a Local Default:

private readonly ILog log;
public MyConsumer(ILog log)
{
    this.log = log ??LogManager.GetLogger("My");
}

In terms of encapsulation, the main problem with such an approach is that it seems like the MyConsumer class can't really make up its mind whether or not it controls the creation of its log dependency. While this is a simplified example, this could become a problem if the ILog instance returned by LogManager wraps an unmanaged resource which should be disposed when it's no longer needed.

Are his arguments in the above excerpt also valid when default implementation of dependency is local? If so, then optional dependencies with local defaults should also be avoided?

3) Pg. 147:

The main problem with Bastard Injection is its use of a FOREIGN DEFAULT ... , we can no longer freely reuse the class because it drags along a dependency we may not want. It also becomes more difficult to do parallel development because the class depends strongly on its DEPENDENCY.

Foreign Default is an implementation of a dependency that's used as a default and is defined in a different assembly than its consumer. Thus with Foreign Default, consumer's assembly will also drag along dependency's assembly.

Is he also implying that Foreign Default makes parallel development more difficult, while Local Default doesn't? If he is, then that doesn't make sense, since I would assume that what makes parallel development difficult is not so much that consumer's assembly has hard reference to dependency's assembly, but rather the fact that consumer class depends on a concrete implementation of a dependency?

thanks

Since there are many questions here, I'll first attempt to provide an synthesis on my view on the subject, and then answer each question explicitly based on this material.

Synthesis

When I wrote the book, I first and foremost attempted to describe the patterns and anti-patterns I'd witnessed in the wild. Thus, the patterns and anti-patterns in the book are first and foremost descriptive, and only to a lesser degree prescriptive. Obviously, dividing them into patterns and anti-patterns imply a certain degree of judgement :)

There are problems with Bastard Injection on multiple levels:

  • Package dependency
  • Encapsulation
  • Ease of use

The most dangerous problem is related to package dependencies. This is the concept I've attempted to make more actionable by the introduction of the terms Foreign Default versus Local Default. The problem with Foreign Defaults is that they drag along hard-coupled dependencies, which makes (de/re)composition impossible. A good resource that deals more explicitly with package management is Agile Principles, Patterns, and Practices.

On the level of encapsulation, code like this is difficult to reason about:

private readonly ILog log;
public MyConsumer(ILog log)
{
    this.log = log ??LogManager.GetLogger("My");
}

Although it protects the class' invariants, the problem is that in this case, null is an acceptable input value. This is not always the case. In the example above, LogManager.GetLogger("My") may only introduce a Local Default. From this code snippet, we have no way to know if this is true, but for the sake of argument, let's assume this for now. If the default ILog is indeed a Local Default, a client of MyConsumer can pass in null instead of ILog. Keep in mind that encapsulation is about making it easy for a client to use an object without understanding all the implementation details. This means that this is all a client sees:

public MyConsumer(ILog log)

In C# (and similar languages) it's possible to pass null instead of ILog, and it's going to compile:

var mc = new MyConsumer(null);

With the above implementation, not only will this compile, but it also works at run-time. According to Postel's law, that's a good thing, right?

Unfortunately, it isn't.

Consider another class with a required dependency; let's call it a Repository, simply because this is such a well-known (albeit overused) pattern:

private readonly IRepository repository;
public MyOtherConsumer(IRepository repository)
{
    if (repository == null)
        throw new ArgumentNullException("repository");

    this.repository = repository;
}

In keeping with encapsulation, a client only sees this:

public MyOtherConsumer(IRepository repository)

Based on previous experience, a programmer may be inclined to write code like this:

var moc = new MyOtherConsumer(null);

This still compiles, but fails at runtime!

How do you distinguish between these two constructors?

public MyConsumer(ILog log)
public MyOtherConsumer(IRepository repository)

You can't, but currently, you have inconsistent behaviour: in one case, null is a valid argument, but in another case, null will cause a runtime exception. This will decrease the trust that every client programmer will have in the API. Being consistent is a better way forward.

In order to make a class like MyConsumer easier to use, you must stay consistent. This is the reason why accepting null is a bad idea. A better approach is to use constructor chaining:

private readonly ILog log;

public MyConsumer() : this(LogManager.GetLogger("My")) {}

public MyConsumer(ILog log)
{
    if (log == null)
        throw new ArgumentNullException("log");

    this.log = log;
}

The client now sees this:

public MyConsumer()
public MyConsumer(ILog log)

This is consistent with MyOtherConsumer because if you attempt to pass null instead of ILog, you will get a runtime error.

While this is technically still Bastard Injection, I can live with this design for Local Defaults; in fact, I sometimes design APIs like this because it's a well-known idiom in many languages.

For many purposes, this is good enough, but still violates an important design principle:

Explicit is better than implicit

While constructor chaining enables a client to use MyConsumer with a default ILog, there's no easy way to figure out what the default instance of ILog would be. Sometimes, that's important too.

Additionally, the presence of a default constructor exposes a risk that a piece of code is going to invoke that default constructor outside of the Composition Root. If that happens, you've prematurely coupled to objects to each other, and once you've done that, you can't decouple them from within the Composition Root.

Thus, there's less risk involved in using plain Constructor Injection:

private readonly ILog log;

public MyConsumer(ILog log)
{
    if (log == null)
        throw new ArgumentNullException("log");

    this.log = log;
}

You can still compose MyConsumer with the default logger:

var mc = new MyConsumer(LogManager.GetLogger("My"));

If you want to make the Local Default more discoverable, you can expose it as a Factory somewhere, e.g. on the MyConsumer class itself:

public static ILog CreateDefaultLog()
{
    return LogManager.GetLogger("My");
}

All this sets the stage for answering the specific sub-questions in this question.

1. Does Bastard Injection anti-pattern also occur when default implementation of dependency is a Local Default?

Yes, technically, it does, but the consequences are less severe. Bastard Injection is first and foremost a description that will enable you to easily identify it when you encounter it.

Please note that the above illustration from the book describes how to refactor away from Bastard Injection; not how to identify it.

2. [Should] optional dependencies with local defaults [...] also be avoided?

From a package dependency perspective, you don't need to avoid those; they are relatively benign.

From a usage perspective, I still tend to avoid them, but it depends on what I'm building.

  • If I create a reusable library (e.g. an OSS project) that many people will use, I may still choose Constructor Chaining in order to make it easier to get started with the API.
  • If I'm creating a class only for use within a particular code base, I tend to entirely avoid optional dependencies, and instead compose everything explicity in the Composition Root.

3. Is he also implying that Foreign Default makes parallel development more difficult, while Local Default doesn't?

No, I don't. If you have a default, the default must be in place before you can use; it doesn't matter whether it's Local or Foreign.

I'm a newbie when it comes to DI and ninject and I'm struggling a bit about when the actual injection should happen and how to start the binding.

I'm using it already in my web application and it working fine there, but now I want to use injection in a class library.

Say I have a class like this:

public class TestClass
{
    [Inject]
    public IRoleRepository RoleRepository { get; set; }
    [Inject]
    public ISiteRepository SiteRepository { get; set; }
    [Inject]
    public IUserRepository UserRepository { get; set; }

    private readonly string _fileName;

    public TestClass(string fileName)
    {
        _fileName = fileName;
    }

    public void ImportData()
    {
        var user = UserRepository.GetByUserName("myname");
        var role = RoleRepository.GetByRoleName("myname");
        var site = SiteRepository.GetByID(15);
        // Use file etc
    }

}

I want to use property injection here because I need to pass in a filename in my constructor. Am I correct in saying that if I need to pass in a constructor parameter, I cannot use constructor injection? If I can use constructor injection with additional parameters, how do I pass those parameters in?

I have a console app that consumes by Test class that looks as follows:

class Program
{
    static void Main(string[] args)
    {
        // NinjectRepositoryModule Binds my IRoleRepository etc to concrete
        // types and works fine as I'm using it in my web app without any
        // problems
        IKernel kernel = new StandardKernel(new NinjectRepositoryModule());

        var test = new TestClass("filename");

        test.ImportData();
    }
}

My problem is that when I call test.ImportData() my repositories are null - nothing has been injected into them. I have tried creating another module and calling

Bind<TestClass>().ToSelf();

as I thought this might resolve all injection properties in TestClass but I'm getting nowhere.

I'm sure this is a trivial problem, but I just can't seem to find out how to go about this.

You are directly newing TestClass, which Ninject has no way of intercepting - remember there's no magic like code transformation intercepting your news etc.

You should be doing kernel.Get<TestClass> instead.

Failing that, you can inject it after you new it with a kernel.Inject( test);

I think there's an article in the wiki that talks about Inject vs Get etc.

Note that in general, direct Get or Inject calls are a Doing It Wrong smell of Service Location, which is an antipattern. In the case of your web app, the NinjectHttpModule and PageBase are the hook that intercepts object creation - there are similar interceptors / logical places to intercept in other styles of app.

Re your Bind<TestClass>().ToSelf(), generally a StandardKernel has ImplicitSelfBinding = true which would make that unnecessary (unless you want to influence its Scope to be something other than .InTransientScope()).

A final style point:- you're using property injection. There are rarely good reasons for this, so you should be using constructor injection instead.

And do go buy Dependency Injection in .NET by @Mark Seemann, who has stacks of excellent posts around here which cover lots of important but subtle considerations in and around the Dependency Injection area.

So i have gotten stuck while trying to get my asmx webservice to use dependency injection and using an IoC to do it. I want my webservice to be able to use my internal business layer services. The webservice is to be used by an external client from a different domain and will mainly be used to send and recieve information about entities such as Orders and Customers.

An example would be:

public class MyService : System.Web.Services.WebService
{
    [WebMethod]
    public string HelloWorld()
    {
        return new MyBusinessService().MyMethod();
    } 
}

public class MyBusinessService : IMyBusinessService
{
    public string MyMethod()
    {
        return "hello";
    }
}

I want to use dependency injection to eliminate the need for "newing" up my service but i cant figure out a way to do this. I can get it to work using poor mans DI, or at least i think it's called "poor mans".

like this:

public class MyService : System.Web.Services.WebService
{
    private IMyBusinessService _myService;

    public MyService(IMyBusinessService myService)
    {
        _myService = myService;
    }

    public MyService() : this(new MyBusinessServie()) { }

    [WebMethod]
    public string HelloWorld()
    {
        return _myService.MyMethod();
    }
}

But I simply cant get my head around how to use a IoC container to inject my dependencies because i cant get the service to run without a parameterless constructor. Please be kind, i am not an experienced programmer and have just started to test dependency injection and got it to work fine on my windows forms application with structuremap but got stuck on this one.

Unfortunately there isn't any way for one to perform constructor injection with web services in ASP.NET. It is a requirement of ASP.NET that you provide a default constructor. The constructor of MyService is about as close to the composition root that you can get with this type of web service, without using a DI container.

With ASP.NET it is not unusual to have multiple composition roots. Which can be the constructors of the individual web services and web pages. If you are using ASP.NET MVC it is the ControllerFactory, which is more DI friendly.

With your implementation the important part isn't to move the construction of the object graph from the web service, as this is your composition root. The main thing to do, is to keep the web service as thin as possible, keep most of the logic in the dependency so it can be tested, or reused. Pulling information out of the HTTP headers is an example of a task that the web service could to then pass off that information to the dependency.

A good book to refer to for DI patterns and techniques is Dependency Injection in .NET by Mark Seemann.

If your web service implemented System.Web.IHttpHandler instead of deriving from System.Web.Services.WebService you could implement your DI like so:

Global.ashx.cs

public class Global : HttpApplication
{
    protected void Application_PreRequestHandlerExecute(object sender, EventArgs e)
    {
        var context = ((HttpApplication)sender).Context;

        var needsMyBusinessService = context.Handler as INeedMyBusinessService;
        if (needsMyBusinessService != null)
            needsMyBusinessService.MyBusinessService = new MyBusinessService();
    }
}

MyService.ashx.cs

public class MyService : IHttpHandler, INeedMyBusinessService
{
    public IMyBusinessService MyBusinessService { get; set; }

    public bool IsReusable { get { return true; } }

    public void ProcessRequest(HttpContext context)
    {
        // uses my dependency
    }
}

INeedMyBusinessService.cs

public interface INeedMyBusinessService
{
    IMyBusinessService MyBusinessService { get; set; }
}

However the catch with this implementation is that is does not work with web services that implement System.Web.Services.WebService as the web service object is not initialized until after the PreRequestHandlerExecute event is call, which is the last event before ProcessRequest is called.

The above example works if you want to have a unique instance for each web service. If you wanted to have the same instance (Singleton lifecycle) of MyBusinessService for each web service request you could implement the Global.ashx.cs file like so:

public class Global : HttpApplication
{
    private static IMyBusinessService businessService;

    protected void Application_Start(object sender, EventArgs e)
    {
        Global.businessService = new MyBusinessService();
    }

    protected void Application_PreRequestHandlerExecute(object sender, EventArgs e)
    {
        var context = ((HttpApplication)sender).Context;

        var needsMyBusinessService = context.Handler as INeedMyBusinessService;
        if (needsMyBusinessService != null)
            needsMyBusinessService.MyBusinessService = Global.businessService;
    }
}

Recently, I have been trying to understand what is the difference between using the Service Locator "anti-pattern" and using the Castle Windsor container. I have found some info here and there on the Internet and I have summarized what I have learned so far in an unfinished blog post.

EDIT: Until now I have been thinking that Dependency Injection is all one would need to guarantee separation. But everywhere I look I see a push in the direction of containers such as Castle Windsor. I would like to clearly understand the reasons. Please... Explain this to me like I'm a 6 year old :)

Funny you should ask to have it explained like you were six years old; here's an explanation like you were five years old :)

everywhere I look I see a push in the direction of containers such as Castle Windsor

Frankly, I think the reason for that is that most people actually don't understand what Dependency Injection is, which means that instead of grasping the concept of Inversion of Control, they go looking for a replacement for the new keyword they're already used to. Then they find a DI Container and (mis)use it as a Service Locator. Unfortunately, that's very easy to do.

This is the reason why, in my book, I explain all the DI concepts without coupling the explanation to any single DI Container. That's actually the majority of the book.

Service Locator and Dependency Injection are two fundamentally different attempts at achieving loose coupling. Service Locator has many disadvantages, and offers no advantages not also offered by DI. This is why I think it's safe to call Service Locator an anti-pattern.

You don't need a DI Container to use DI; in fact, I would say that unless you take a rather sophisticated approach, it's probably better to avoid one.

So Inversion Of Control is a vague description, so Dependency Injection became the new definition. This is a very, very powerful solution and is quite possibly just as confusing to someone whom has never encountered it.

So in my quest to not be a deer in headlights, I read up. I found several terrific books and online post. But like all wonderful things, more questions arose rather then answers.

The problem, absorbing variables from an unknown project to be implemented once they've been introduced into my project.

The solution:

public interface ISiteParameter
{
    Guid CustomerId { get; set; }
    string FirstName { get; set; }
    string LastName { get; set; }
    string Phone { get; set; }
}

My injector:

public interface IInjectSiteParameter
{
     void InjectSite(ISiteParameter dependant);
}

Then I created this:

public class SiteContent : IInjectSiteParameter
{
    private ISiteParameter _dependent;

    #region Interface Member:
    public void InjectSite(ISiteParameter dependant)
    {
        _dependant = dependant;
    }
    #endregion
}

Then to implement it with a Shared Reference to be Fed Variables I created a class to be implemented like:

public class SiteParameters : ISiteParameter
{    
   public Guid Customer Id { get; set; }
   public string FirstName { get; set; }
   public string LastName  { get; set; }
   public string Phone { get; set; }
}

Now the SiteParameters Class will be referenced by the other project; which will allow me to actually call these properties whenever and wherever with:

ISiteParameter i = new ISiteParameter();
MessageBox.Show(i.Guid + i.FirstName + i.LastName + i.Phone);

That was the implementation, but my question is this... When do I do I use?

  • Constructor Injection
  • Setter Injection
  • Interface Injection

When would you use one or the other? And for the task I mentioned should of I implemented such a difficult task to adjust for any changes made to the other project?

Did I fall off the curve in my thought process?

Pulled from chapter 4 of Dependency Injection in .NET by Mark Seemann

Constructor injection should be your default choice for DI. It addresses the most common scenario where a class requires one or more dependencies. If the depending class absolutely can’t function without the dependency that guarantee is valuable.

Property injection should only be used when the class you’re developing has a good local default and you still want to enable callers to provide different implementations of the class’s dependency. Property injection may also be used in cases where frameworks require you to have default constructors, like ASP.NET pages.

Method injection is best used when the dependency can vary with each method call. This can be the case when the dependency itself represents a value, but is often seen when the caller wishes to provide the consumer with information about the context in which the operation is being invoked.

How do I connect the various pieces of my Web API Castle Windsor DI code so that the Controller's routing selects the correct interface implementation?

Note: After several false starts/dead ends and partial victories (here and here and here), I am going to bountify this ASAP for the maximum 500 points. But I'm only going to award a really good answer - IOW, one that is clear enough that I can understand it and "plug it in" to my project so that I can hook a given concrete class to a particular Controller.

Here goes nothing: I have a Web API ("MVC") project. Really, though, this server project has no "V" (View), so maybe a better acronym would be MRC (Model/Repository/Controller).

At any rate, I'm trying to add DI to it using Castle Windsor.

I grok, and dig, the concept of swapping out concrete classes via constructor interface args. Just how to implement this functionality, though,

has been a beast I've been wrestling with, and I'm quite bruised and bloody at present, with mussed-up hair and mud-encrusted nostrils to boot.

I have, I think, most of the code I need - to start with, anyway. With DI in mind, I've now got a "DIPlumbing" folder, and a "DIInstallers" folder. The "DIPlumbing" folder contains two classes: WindsorCompositionRoot.cs, and WindsorControllerFactory.cs.

The "DIInstallers" folder has, for now, three files, namely ISomethingProvider.cs, SomethingProvider.cs, and SomethingProviderInstaller.cs

SomethingProviderInstaller seems to be key in connecting the interfaces/classes in DIInstallers to the stuff in the DIPlumbing folder.

(I have also modified Global.asax.cs to replace the default controller routing business with the Castle Windsor replacement).

But I'm confused as to what classes I should be placing in the DIInstallers folder. Are these supposed to take the place of my Repositories (which likewise have an interface and a concrete class that implements that interface for each model)? IOW, should I basically move my Repository code into the DIInstallers folder - and then get rid of the IRepository and Repository units?

This, of course, would cause necessary changes to be made in the Controller classes, which as of now reference Repository classes.

Or do the Repositories and DIInstallers classes coexist? If so, what is the connection/affiliation between the Controllers, Installers, and Repositories?

It seems the more I read up on DI and Castle Windsor, the more confused I get. I don't know if I'm too dense for it, or if I'm trying to make it harder than it is, or if conflicting styles of using/presenting it are the problem. The bottom line is: I'm stuck in quicksand and need Johnny Quest to extend a sturdy bamboo rod.

The best answer of all, perhaps, and probably too much to ask for, would be a visual representation of how all these components - Controllers, Models, Repositories, Installers, Global.asax.cs, composition roots, factories, providers, etc., relate to each other.

For purposes of "full disclosure," I will add what I hope are the key elements of my code below to show what I've got and how it (hopefully) connects to each other.

Composition Root:

public class WindsorCompositionRoot : IHttpControllerActivator
{
    private readonly IWindsorContainer container;

    public WindsorCompositionRoot(IWindsorContainer container)
    {
        this.container = container;
    }

    public IHttpController Create(
        HttpRequestMessage request,
        HttpControllerDescriptor controllerDescriptor,
        Type controllerType)
    {
        var controller =
            (IHttpController)this.container.Resolve(controllerType);

        request.RegisterForDispose(
            new Release(
                () => this.container.Release(controller)));

        return controller;
    }

    private class Release : IDisposable
    {
        private readonly Action release;

        public Release(Action release)
        {
            this.release = release;
        }

        public void Dispose()
        {
            this.release();
        }
    }
}

Controller Factory:

public class WindsorControllerFactory : DefaultControllerFactory
{
    private readonly IKernel kernel;

    public WindsorControllerFactory(IKernel kernel)
    {
        this.kernel = kernel;
        //According to my understanding of http://docs.castleproject.org/Windsor.Typed-Factory-Facility.ashx, I might need this:
        kernel.AddFacility<TypedFactoryFacility>();
    }

    protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
    {
        if (controllerType == null)
        {
            throw new HttpException(404, string.Format("The controller for path '{0}' could not be found.", requestContext.HttpContext.Request.Path));
        }
        return (IController)kernel.Resolve(controllerType);
    }

    public override void ReleaseController(IController controller)
    {
        kernel.ReleaseComponent(controller);
    }

// Note: The "Something" below will hopefully eventually be "Departments" and then other classes now represented in Models and their corresponding Repositories and Controllers

ISomethingProvider:

public interface ISomethingProvider
{
    // These are placeholder methods; I don't know which I will need yet...
    //bool Authenticate(string username, string password, bool createPersistentCookie);
    //void SignOut();
}

SomethingProvider:

public class SomethingProvider : ISomethingProvider
{
    // TODO: Implement methods in ISomethingProvider, once they have been added
}

SomethingProviderInstaller:

public class SomethingProviderInstaller : IWindsorInstaller
{
    public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        container.Register(Classes.FromThisAssembly()
                               .BasedOn(typeof(ISomethingProvider))
                               .WithServiceAllInterfaces());
        // From http://app-code.net/wordpress/?p=676; see also http://devlicio.us/blogs/krzysztof_kozmic/archive/2009/12/24/castle-typed-factory-facility-reborn.aspx
        container.AddFacility<TypedFactoryFacility>();
        container.Register(Component.For<IMyFirstFactory>().AsFactory()); 
    }
}

Controller:

public class DepartmentsController : ApiController
{
    private readonly IDepartmentRepository _deptsRepository;

    public DepartmentsController(IDepartmentRepository deptsRepository)
    {
        if (deptsRepository == null)
        {
            throw new ArgumentNullException("deptsRepository is null");
        }
        _deptsRepository = deptsRepository;
    }

    public int GetCountOfDepartmentRecords()
    {
        return _deptsRepository.Get();
    }

    public IEnumerable<Department> GetBatchOfDepartmentsByStartingID(int ID, int CountToFetch)
    {
        return _deptsRepository.Get(ID, CountToFetch);
    }
. . .
}

IRepository:

public interface IDepartmentRepository
{
    int Get();
    IEnumerable<Department> Get(int ID, int CountToFetch);
}

Repository:

public class DepartmentRepository : IDepartmentRepository
{
    private readonly List<Department> departments = new List<Department>();

    public DepartmentRepository()
    {
        using (var conn = new OleDbConnection(
            @"Provider=Microsoft.ACE.OLEDB.12.0;[bla]"))
        {
            using (var cmd = conn.CreateCommand())
            {
                cmd.CommandText = "SELECT td_department_accounts.dept_no, IIF(ISNULL(t_accounts.name),'No Name provided',t_accounts.name) AS name FROM t_accounts INNER JOIN td_department_accounts ON t_accounts.account_no = td_department_accounts.account_no ORDER BY td_department_accounts.dept_no";
                cmd.CommandType = CommandType.Text;
                conn.Open();
                int i = 1;
                using (OleDbDataReader oleDbD8aReader = cmd.ExecuteReader())
                {
                    while (oleDbD8aReader != null && oleDbD8aReader.Read())
                    {
                        int deptNum = oleDbD8aReader.GetInt16(0);
                        string deptName = oleDbD8aReader.GetString(1);
                        Add(new Department { Id = i, AccountId = deptNum, Name = deptName });
                        i++;
                    }
                }
            }
        }
    }

    public int Get()
    {
        return departments.Count;
    }

    private Department Get(int ID) // called by Delete()
    {
        return departments.First(d => d.Id == ID);
    }

    public IEnumerable<Department> Get(int ID, int CountToFetch)
    {
        return departments.Where(i => i.Id > ID).Take(CountToFetch);
    }
. . .
}

Global.asax.cs:

public class WebApiApplication : System.Web.HttpApplication
{
    private static IWindsorContainer container;

    protected void Application_Start()
    {

        AreaRegistration.RegisterAllAreas();
        GlobalConfiguration.Configure(WebApiConfig.Register);
        BootstrapContainer();

        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
    }

    private static void BootstrapContainer()
    {
        container = new WindsorContainer().Install(FromAssembly.This());
        var controllerFactory = new WindsorControllerFactory(container.Kernel);

        ControllerBuilder.Current.SetControllerFactory(controllerFactory);

        GlobalConfiguration.Configuration.Services.Replace(
            typeof(IHttpControllerActivator), new WindsorCompositionRoot(container));
    }

    protected void Application_End()
    {
        container.Dispose();
    }

UPDATE

In trying to run the server, so that it could test it with Fiddler2 to see just what is being passed around, it failed on this line in WindsorControllerFactory:

public WindsorControllerFactory(IKernel kernel)
{
    this.kernel = kernel;
    kernel.AddFacility<TypedFactoryFacility>(); <-- throws exception here
}

...with "*System.ArgumentException was unhandled by user code HResult=-2147024809 Message=Facility of type 'Castle.Facilities.TypedFactory.TypedFactoryFacility' has already been registered with the container. Only one facility of a given type can exist in the container. Source=Castle.Windsor StackTrace: at Castle.MicroKernel.DefaultKernel.AddFacility(String key, IFacility facility) at Castle.MicroKernel.DefaultKernel.AddFacility(IFacility facility) at Castle.MicroKernel.DefaultKernel.AddFacilityT at HandheldServer.DIPlumbing.WindsorControllerFactory..ctor(IKernel kernel) in c:\HandheldServer\HandheldServer\DIPlumbing\WindsorControllerFactory.cs:line 28 at HandheldServer.WebApiApplication.BootstrapContainer() in c:\HandheldServer\HandheldServer\Global.asax.cs:line 69 at HandheldServer.WebApiApplication.Application_Start() in c:\HandheldServer\HandheldServer\Global.asax.cs:line 39*"

UPDATE 2

In response to Cristiano's answer:

So are you saying I should add the following two files to my Installers folder (I do have a DIInstallers folder already)

PlatypusInstallerFactory.cs:

public class PlatypusInstallerFactory : InstallerFactory
{
    public override IEnumerable<Type> Select(IEnumerable<Type> installerTypes)
    {
        var windsorInfrastructureInstaller = installerTypes.FirstOrDefault(it => it == typeof(WindsorInfrastructureInstaller));

        var retVal = new List<Type>();
        retVal.Add(windsorInfrastructureInstaller);
        retVal.AddRange(installerTypes
            .Where(it =>
                typeof(IWindsorInstaller).IsAssignableFrom(it) &&
                !retVal.Contains(it)
                ));

        return retVal;
    }
}

WindsorInfrastructureInstaller.cs:

public class WindsorInfrastructureInstaller : IWindsorInstaller
{
    public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        container.AddFacility<TypedFactoryFacility>();
    }
}

In your global.asax you'll create&use you installer factory as following

   var installerFactory = new PlatypusInstallerFactory();
   container.Install(FromAssembly.This(installerFactory));

If yes, what will that do for me? Does the above automagically register my Controller and/or Repository classes?

UPDATE 3

I am now using a lot of code from [http://blog.kerbyyoung.com/2013/01/setting-up-castle-windsor-for-aspnet.html#comment-form]

The key parts are, I think:

global.asax.cs:

private static IWindsorContainer _container;

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();

    WebApiConfig.Register(GlobalConfiguration.Configuration);
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);

    ConfigureWindsor(GlobalConfiguration.Configuration);
}

public static void ConfigureWindsor(HttpConfiguration configuration)
{
    _container = new WindsorContainer();
    _container.Install(FromAssembly.This());
    _container.Kernel.Resolver.AddSubResolver(new CollectionResolver(_container.Kernel, true));
    var dependencyResolver = new WindsorDependencyResolver(_container);
    configuration.DependencyResolver = dependencyResolver;
}  

WindsorDependencyResolver.cs:

namespace HandheldServer
{
    public class WindsorDependencyResolver : System.Web.Http.Dependencies.IDependencyResolver
    {
        private readonly IWindsorContainer _container;

        public WindsorDependencyResolver(IWindsorContainer container)
        {
            _container = container;
        }

        public IDependencyScope BeginScope()
        {
            return new WindsorDependencyScope(_container);
        }

        public object GetService(Type serviceType)
        {
            if (!_container.Kernel.HasComponent(serviceType))
            {
                return null;
            }
            return this._container.Resolve(serviceType);
        }

        public IEnumerable<object> GetServices(Type serviceType)
        {
            if (!_container.Kernel.HasComponent(serviceType))
            {
                return new object[0];
            }

            return _container.ResolveAll(serviceType).Cast<object>();
        }

        public void Dispose()
        {
            _container.Dispose();
        }
    }

    public class WindsorDependencyScope : IDependencyScope
    {
        private readonly IWindsorContainer _container;
        private readonly IDisposable _scope;

        public WindsorDependencyScope(IWindsorContainer container)
        {
            this._container = container;
            this._scope = container.BeginScope(); 
        }

        public object GetService(Type serviceType)
        {
            if (_container.Kernel.HasComponent(serviceType))
            {
                return _container.Resolve(serviceType);
            }
            else
            {
                return null;
            }
        }

        public IEnumerable<object> GetServices(Type serviceType)
        {
            return this._container.ResolveAll(serviceType).Cast<object>();
        }

        public void Dispose()
        {
            this._scope.Dispose();
        }
    }

    public class ApiControllersInstaller : IWindsorInstaller
    {
        public void Install(Castle.Windsor.IWindsorContainer container, Castle.MicroKernel.SubSystems.Configuration.IConfigurationStore store)
        {
            container.Register(Classes.FromThisAssembly() // should it be Types instead of Classes?
             .BasedOn<ApiController>()
             .LifestylePerWebRequest());
        }
    }

    // This idea from https://github.com/argeset/set-locale/blob/master/src/client/SetLocale.Client.Web/Configurations/IocConfig.cs
    public class ServiceInstaller : IWindsorInstaller
    {
        public void Install(IWindsorContainer container, IConfigurationStore store)
        {
            container.Register(
                Component.For<IDeliveryItemRepository>().ImplementedBy<DeliveryItemRepository>().LifestylePerWebRequest(),
                Component.For<IDeliveryRepository>().ImplementedBy<DeliveryRepository>().LifestylePerWebRequest(),
                Component.For<IDepartmentRepository>().ImplementedBy<DepartmentRepository>().LifestylePerWebRequest(),
                Component.For<IExpenseRepository>().ImplementedBy<ExpenseRepository>().LifestylePerWebRequest(),
                Component.For<IInventoryItemRepository>().ImplementedBy<InventoryItemRepository>().LifestylePerWebRequest(),
                Component.For<IInventoryRepository>().ImplementedBy<InventoryRepository>().LifestylePerWebRequest(),
                Component.For<IItemGroupRepository>().ImplementedBy<ItemGroupRepository>().LifestylePerWebRequest());
        }
    }
}

UPDATE 4

This question is probably too general for SO, so I posted it on "Programmers"

UPDATE 5

Note: According to "The DI Whisperer" (Mark Seemann), IDependencyResolver should not be used, because it lacks a Release method (p. 207 of his book)

In answer to my own question, I would simply say: There are no shortcakes! Without stopping go or further ado, go here and get this book. Resign yourself to take the time necessary to read it carefully.

So I'm not the only one; here's a quote from Jeff Beck, who wrote that book's foreword: "Often those who start using DI quickly find themselves lost in a sea of confusion."

I'm trying to improve the performance of my IoC container. We are using Unity and SimpleInjector and we have a class with this constructor:

public AuditFacade(
    IIocContainer container, 
    Func<IAuditManager> auditManagerFactory,
    Func<ValidatorFactory> validatorCreatorFactory, 
    IUserContext userContext,
    Func<ITenantManager> tenantManagerFactory, 
    Func<IMonitoringComponent> monitoringComponentFactory)
    : base(container, auditManagerFactory, GlobalContext.CurrentTenant, 
          validatorCreatorFactory, userContext, tenantManagerFactory)
{
    _monitoringComponent = new Lazy<IMonitoringComponent>(monitoringComponentFactory);
}

I also have another class with this constructor:

public AuditTenantComponent(Func<IAuditTenantRepository> auditTenantRepository)
{
    _auditTenantRepository = new Lazy<IAuditTenantRepository>(auditTenantRepository);
}

I'm seeing that the second one gets resolved in 1 millisecond, most of the time, whereas the first one takes on average 50-60 milliseconds. I'm sure the reasoning for the slower one is because of the parameters, it has more parameters. But how can I improve the performance of this slower one? Is it the fact that we are using Func<T> as parameters? What can I change if it is causing the slowness?

There is possibly a lot to improve on your current design. These improvements can be placed in five different categories, namely:

  1. Possible abuse of base classes
  2. Use of Service Locator anti-pattern
  3. Unneeded use of ambient context
  4. Leaky abstractions
  5. Injection Constructors should be simple

Possible abuse of base classes

The general consensus is that you should prefer composition over inheritance. Inheritance is often overused and often adds more complexity compared to using composition. With inheritance the derived class is strongly coupled to the base class implementation. I often see a base class being used as practical utility class containing all sorts of helper methods for cross-cutting concerns and other behavior that some of the derived classes may need.

An often better approach is to remove the base class all together and inject a service into the implementation (the AuditFacade class in your case) that exposed just the functionality that the service needs. Or in case of cross-cutting concerns, don't inject that behavior at all, but wrap the implementation with a decorator that extends the class'es behavior with cross-cutting concerns.

In your case, I think the complication is clearly happening, since 6 out of 7 injected dependencies are not used by the implementation, but are only passed on to the base class. In other words, those 6 dependencies are implementation details of the base class, while the implementation still is forced to know about them. By abstracting (part of) that base class behind a service, you can minimize the number of dependencies that AuditFacade needs to two dependencies: the Func<IMonitoringComponent> and the new abstraction. The implementation behind that abstraction will have 6 constructor dependencies, but the AuditFacade (and other implementations) are oblivious to that.

Use of Service Locator anti-pattern

The AuditFacade depends on an IIocContainer abstraction and this is very like an implementation of the Service Locator pattern. Service Locator should be considered an anti-pattern because:

it hides a class' dependencies, causing run-time errors instead of compile-time errors, as well as making the code more difficult to maintain because it becomes unclear when you would be introducing a breaking change.

There are always better alternatives to injecting your container or an abstraction over your container into application code. Do note that at some times you might want to inject the container into factory implementations, but at long as those are placed inside your Composition Root, there's no harm in that, since Service Locator is about roles, not mechanics.

Unneeded use of ambient context

The static GlobalContext.CurrentTenant property is an implementation of the Ambient Context pattern. Mark Seemann writes about this pattern in his book and he states:

AMBIENT CONTEXT should only be used in the rarest of cases. In most cases, CONSTRUCTOR INJECTION or PROPERTY INJECTION is far more suitable. [paragraph 4.4.2. page 128]

The use in this case is really weird IMO, because you grab the current tenant from some static property from inside your constructor to pass it on to the base class. Why doesn't the base class call that property itself?

But no one should call that static property. The use of those static properties makes your code harder to read and maintain. It makes unit testing harder and since your code base will usually be littered with calls to such static, it becomes a hidden dependency; it has the same downsides as the use of Service Locator.

Leaky abstraction

A Leaky Abstraction is a Dependency Inversion Principle violation, where the abstraction violates the second part of the principle, namely:

B. Abstractions should not depend on details. Details should depend on abstractions.

Although Lazy<T> is not abstractions by itself (Lazy<T> is a concrete type), it can become leaky abstraction when used as constructor argument. For instance, if you are injecting an Lazy<IMonitoringComponent> instead of an IMonitoringComponent directly (which is what you are basically doing in your code), the new Lazy<IMonitoringComponent> abstraction leaks implementation details. This Lazy<IMonitoringComponent> communicates to the consumer that the used IMonitoringComponent implementation is expensive or time consuming to create. But why should the consumer care about this?

But there are more problems with this. If at one point in time the used IUserContext implementation becomes costly to create, we must start to make sweeping changes throughout the application (a violation of the Open/Closed Principle) because all IUserContext dependencies need to be changed to Lazy<IUserContext> and all consumers of that IUserContext must be changed to use userContext.Value. instead. And you'll have to change all your unit tests as well. And what happens if you forget to change one IUserContext reference to Lazy<IUserContext> or when you accidentally depend on IUserContext when you create a new class? You have a bug in your code, because at that point the user context implementation is created right away and this will cause a performance problem (this causes a problem, because that is the reason you are using Lazy<T> in the first place).

So why are we exactly making sweeping changes to our code base and polluting it with that extra layer of indirection? There is no reason for this. The fact that a dependency is costly to create is an implementation detail. You should hide it behind an abstraction. Here's an example:

public class LazyMonitoringComponentProxy : IMonitoringComponent {
    private Lazy<IMonitoringComponent> component;

    public LazyMonitoringComponentProxy(Lazy<IMonitoringComponent> component) {
        this.component = component;
    }

    void IMonitoringComponent.MonitoringMethod(string someVar) {
        this.component.Value.MonitoringMethod(someVar);
    }
}

In this example we've hidden the Lazy<IMonitoringComponent> behind a proxy class. This allows us to replace the original IMonitoringComponent implementation with this LazyMonitoringComponentProxy without having to make any change to the rest of the applicaiton. With Simple Injector, we can register this type as follows:

container.Register<IMonitoringComponent>(() => new LazyMonitoringComponentProxy(
    new Lazy<IMonitoringComponent>(container.GetInstance<CostlyMonitoringComp>));

And just as Lazy<T> can be abused as leaky abstraction, the same holds for Func<T>, especially when you're doing this for performance reasons. When applying DI correctly, there is most of the time no need to inject factory abstractions into your code such as Func<T>.

Do note that if you are injecting Lazy<T> and Func<T> all over the place, you are complicating your code base unneeded.

Injection Constructors should be simple

But besides Lazy<T> and Func<T> being leaky abstractions, the fact that you need them a lot is an indication of a problem with your application, because Injection Constructors should be simple. If constructors take a long time to run, your constructors are doing too much. Constructor logic is often hard to test and if such constructor makes a call to the database or requests data from HttpContext, verification of your object graphs becomes much harder to the point that you might skip verification all together. Skipping verification of the object graph is a terrible thing to do, because this forces you to click through the complete application to find out whether or not your DI container is configured correctly.

I hope this gives you some ideas about improving the design of your classes.

Please note: I have just started using AutoFac to learn about DI and IoC.

Is dependency injection supposed to be initialized in the controllers constructor?

How is this?

private IMyService iMyService;
public HomeController(IMyServices myService)
{
    iMyService = myService;
}

Different from...

public IMyService iMyService = new MyService();

Lastly, it seems like the dependency still exists.

Edit: Fixed typo, new MyService(); was new IMyService();

Edit, the dependency always "exists" but it was moved outside of the class notice that IMyServices can now be defined in the same project as HomeController when MyService is in totally another class. and your DLL with HomeController can compile without knowing about your MyService dll effectivly decoupling them.


this is a very complex topic and you should read a book about it. reading blogs videos and so on didn;t really help.

this is a good book. http://www.amazon.com/Dependency-Injection-NET-Mark-Seemann/dp/1935182501

this is a great vidoe lecture series first 5 videos are about DI in general http://channel9.msdn.com/Blogs/mtaulty/Prism--Silverlight-Part-1-Taking-Sketched-Code-Towards-Unity

initilization is focused in a COMPOSITION ROOT http://blog.ploeh.dk/2011/07/28/CompositionRoot/

and the pattern you shown here is CONSTRUCTOR INJECTION

http://programmers.stackexchange.com/questions/177649/what-is-constructor-injection

Possible Duplicate:
Inversion of Control < Dependency Injection

Could anyone please help me to understand DI and IOC with simple C# example please? As I understand IOC is the inversion of control flow (which means nothing to me) and DI means injecting interfaces via properties or constructors. Not sure how these two are related.

Thank you.

I highly recommend you to read Dependency Injection in .NET book, it in details describes all aspects with comprehensive code examples. For the inversion of control you should refer to another book by Robert Martin: Agile Principles, Patterns, and Practices in C#. It in details describes SOLID principles with examples and understandable explanations. These two books really helped me to understand these principles.

I am completely new to Unit test case writing. I am using MVVMLigh with WPF. Is it necessary to use some third party test framework or .Net Unit test framework it enough? Also how to handle static class in unit test case? In this case AppMessages class.

Can some one please guide me how to write unit cases for following piece of code:

public MyViewModel(Participant participant)
{    
    if (participant != null)
    {
        this.ParentModel = parentModel;
        OkCommand = new RelayCommand(() => OkCommandExecute());
        CalculateAmountCommand = new RelayCommand(() => CalculateAmount());        
    }
    else
    {
        ExceptionLogger.Instance.LogException(Constants.ErrorMessages.FinancialLineCanNotBeNull, "FinancialLineViewModel");
        AppMessages.DisplayDialogMessage.Send(Constants.ErrorMessages.FinancialLineCanNotBeNull, MessageBoxButton.OK, Constants.DefaultCaption, null);
    }
}

public static class AppMessages
{
    enum AppMessageTypes
    {
        FinancialLineViewDisplay,
        FinancialLineViewClose,
        DisplayDialogMessage
    }

    public static class DisplayDialogMessage
    {
        public static void Send(string message, MessageBoxButton button, string caption, System.Action<MessageBoxResult> action)
        {
            DialogMessage dialogMessage = new DialogMessage(message, action)
            {
                Button = button,
                Caption = caption
            };

            Messenger.Default.Send(dialogMessage, AppMessageTypes.DisplayDialogMessage);
        }

        public static void Register(object recipient, System.Action<DialogMessage> action)
        {
            Messenger.Default.Register<DialogMessage>(recipient, AppMessageTypes.DisplayDialogMessage, action);
        }
    }
}

public class ExceptionLogger
{
    private static ExceptionLogger _logger;
    private static object _syncRoot = new object();

    public static ExceptionLogger Instance
    {
        get
        {
            if (_logger == null)
            {
                lock (_syncRoot)
                {
                    if (_logger == null)
                    {
                        _logger = new ExceptionLogger();
                    }
                }
            }

            return _logger;
        }
    }

    public void LogException(Exception exception, string additionalDetails)
    {
        LogException(exception.Message, additionalDetails);
    }

    public void LogException(string exceptionMessage, string additionalDetails)
    {
        MessageBox.Show(exceptionMessage);
    }
}

About testability

Due to using of singletons and static classes MyViewModel isn't testable. Unit testing is about isolation. If you want to unit test some class (for example, MyViewModel) you need to be able to substitute its dependencies by test double (usually stub or mock). This ability comes only when you providing seams in your code. One of the best technique to provide seams is Dependency Injection. The best resource for learning DI is book from Mark Seemann (Dependency Injection in .NET).

You can't easily substitute calls of static members. But if you use much static members then your design isn't perfect.

Of course, you can use unconstrained isolation framework such as Typemock Isolator, JustMock or Microsoft Fakes to fake static method calls but it costs money and it don't push you to better design. This frameworks are great for creating test harness for legacy code.

About design

  1. Constructor of MyViewModel is doing too much. Constructors should be simple.
  2. If dependecy is null then constructor must throw ArgumentNullException but not silently log about error. Throwing exception is a clear indication that your object isn't usable.

About testing framework

You can use any unit testing framework you like. Even MSTest, but personally I don't recommend it. NUnit and xUnit.net is MUCH better.

Further reading

  1. Mark Seeman - Dependency Injection in .NET
  2. Roy Osherove - The Art of Unit Testing (2nd Edition)
  3. Michael Feathers - Working Effectively with Legacy Code
  4. Gerard Meszaros - xUnit Test Patterns

Sample (using MvvmLight, NUnit and NSubstitute)

public class ViewModel : ViewModelBase
{
    public ViewModel(IMessenger messenger)
    {
        if (messenger == null)
            throw new ArgumentNullException("messenger");

        MessengerInstance = messenger;
    }

    public void SendMessage()
    {
        MessengerInstance.Send(Messages.SomeMessage);
    }
}

public static class Messages
{
    public static readonly string SomeMessage = "SomeMessage";
}

public class ViewModelTests
{
    private static ViewModel CreateViewModel(IMessenger messenger = null)
    {
        return new ViewModel(messenger ?? Substitute.For<IMessenger>());
    }

    [Test]
    public void Constructor_WithNullMessenger_ExpectedThrowsArgumentNullException()
    {
        var exception = Assert.Throws<ArgumentNullException>(() => new ViewModel(null));
        Assert.AreEqual("messenger", exception.ParamName);
    }

    [Test]
    public void SendMessage_ExpectedSendSomeMessageThroughMessenger()
    {
        // Arrange
        var messengerMock = Substitute.For<IMessenger>();
        var viewModel = CreateViewModel(messengerMock);

        // Act
        viewModel.SendMessage();

        // Assert
        messengerMock.Received().Send(Messages.SomeMessage);
    }
}

I am using dependency injection for quite some time and I really like the technique, but I often have a problem of too many dependencies that should be injected 4 - 5 which seems to much.

But I cannot find a way to make it simpler. For instance I have a class with some business logic that sends messages, it accepts two other business logic dependencies to do what is needed (one to translate data to messages sent, and one to translate messages that are received).

But apart from this it needs some "technical" dependencies like ILogger, ITimerFactory (because it needs to create timers inside), IKeyGenerator (to generate unique keys).

So the whole list grows pretty big. Are there any good common ways to reduce the number of dependencies?

One way to handle those is to refactor towards Aggregates (or Facades). Mark Seemann wrote a good article on it, check it out (actually I highly recommend his book as well, just saying). So say you have the following (as taken from the article):

public OrderProcessor(IOrderValidator validator,
                      IOrderShipper shipper,
                      IAccountsReceivable receivable,
                      IRateExchange exchange,
                      IUserContext userContext)

You can refactor it to:

public OrderProcessor(IOrderValidator validator,
                      IOrderShipper shipper,
                      IOrderCollector collector)

Where OrderCollector is a facade (it wraps the previous 3 dependencies):

public OrderCollector(IAccountsReceivable receivable,
                      IRateExchange exchange,
                      IUserContext userContext)

I hope this helps.

EDIT

In terms of the cross-cutting concerns (logging and caching for example) and a strategy to handle them, here is a suggestion (that's what I usually do), say you have the following:

public interface IOrderService
{
    void DoAwesome();
}

public class OrderService : IOrderService
{
    public void DoAwesome()
    {
        // do your thing here ... no logging no nothing
    }
}

Here I'd use the decorator pattern to create an OrderService that has logging enabled:

public class OrderServiceWithLogging : IOrderService
{
    private readonly IOrderService _orderService;
    private readonly ILogger _logger;

    public OrderServiceWithLogging(IOrderService orderService, ILogger logger)
    {
        _orderService = orderService;
        _logger = logger;
    }

    public void DoAwesome()
    {
        _orderService.DoAwesome();
        _logger.Log("Awesome is done!");
    }
}

It might look like a bit of overhead but IMHO, it's clean and testable.

Another way would be to go into Aspect Oriented Programming and look into concepts such as interception, where basically you intercept certain method calls and perform tasks as a result. Many DI frameworks (I wanna say all?) support interception, so that might be something that you prefer.

My ASP.NET MVC app starts very very slowly (minimum 20 seconds till first render). It has lots of assemblies in the bin folder.

I understand the runtime scans all assemblies, looking for Controller classes. I imagine this kind of reflection would be very slow. We're on shared hosting, so the first load is terribly slow, and there are lots of first loads, because the app pool is recycled frequently.

I've seen lots of examples of manually registering controllers using IOC containers. We don't use IOC.

So, how do I manually register controllers? I'd like to do this in Application_Start, or something like that.

Edit regarding some of the comments. I know that this won't solve the slow start problem entirely. But it might help. So no point in dissuading me from trying, because we've decided to try :).

You need to override DefaultControllerFactory. Then set it at Application_Start.

ControllerBuilder.Current.SetControllerFactory(typeof (CustomControllerFactory));

Example -

FYI: Mark Seemann (author of Dependency Injection in .Net) said "creating an object instance is something the .NET Framework does extremely fast. Any performance bottleneck your application may have will appear in other places."

What .net/c# focused books are there that teach how to develop applications using SOLID principles, unit testing, IoC, etc?

I've watched a few videos on the SOLID principles, but I'd love to learn more about it and in detail on how to go about designing larger scale applications etc.

First of all, it is this book:

http://www.amazon.com/Agile-Principles-Patterns-Practices-C/dp/0131857258/ref=sr_1_5?ie=UTF8&qid=1308502374&sr=8-5

Robert Martin - it is a person who introduced SOLID principles.

And I am looking forward to read this book about DI in .Net:

http://www.amazon.com/gp/product/1935182501/ref=ox_sc_act_title_3?ie=UTF8&m=ATVPDKIKX0DER

About unit testing here is very good book: http://www.amazon.com/Art-Unit-Testing-Examples-Net/dp/1933988274

How can I check whether the executing code is running in either IIS or NUnit? The reason I ask is because I want to load a different NHibernate configuration based on whether my site is live or running in NUnit.

var configuration = new Configuration();
if (IsRunningOnIIS)
{
    configuration.Configure();
}
else // if (IsRunningInNUnit)
{
    configuration.Configure("hibernate.cfg.test.xml");
}

This is a wrong approach and you should be using dependency injection. But since you asked:

Process currentProcess = Process.GetCurrentProcess();
if(currentProcess.ProcessName == "w3wp") {
    // IIS
} else if (currentProcess.ProcessName == "nunit-agent") {
    // NUnit
}

or

if(HttpContext.Current != null) {
    // IIS
} else {
    // NOT IIS
}

You may need to replace 'nunit-agent' with the name of your runner if you using something like Resharper. Ideally though, you would inject Configuration into initialization code on application startup (manually or using DI container). Order Dependency Injection in .NET book.

I am currently working on a project that requires us to write unit tests. This is an area where my knowledge is limited. After researching over the last few days I have seen multiple examples showing how to write basic tests that assert if a string is equal to another string.

However, what I am still unclear on is how to approach unit testing as a whole. I have an example method that I need to test below:

public static SearchResults GetSearchResults(SearchFormModel searchForm, int currentItemCount, int skip)
    {
        var results = new SearchResults();
        var client = new RestClient(Settings.Default.SearchWebServiceUrl);
        try
        {
            var request = new RestRequest("{0}", Method.GET);
            if (!searchForm.FirstName.IsNullOrEmpty()){request.AddParameter("forenames",searchForm.FirstName);}
            if (!searchForm.LastName.IsNullOrEmpty()) { request.AddParameter("surname", searchForm.LastName); }

            request.AddUrlSegment("0", "Basic");

            request.AddHeader("Accept", "application/json");

            var response = client.Execute<SearchResult>(request);
            if (response.ResponseStatus != ResponseStatus.Completed)
            {
                if (response.ErrorException != null)
                {
                    SendErrorEmail(response.ErrorException.Message);                        
                }
                throw new Exception(Settings.Default.SearchGenericError);
            }

            if (response.Data != null)
            {
                results.Valid = response.Data.Valid;
                var error = response.Data.Error;
                if (!string.IsNullOrEmpty(error)){error = Settings.Default.SearchGenericError;}
                results.Error = error;
                if (response.Data.SearchResults != null)
                {                        
                    results.SearchResults = new List<SearchResult>(response.Data.SearchResults );
                }
            }
            else
            {
                throw new Exception(Settings.Default.SearchGenericError);
            }
        }
        catch (Exception ex)
        {
            registrantList.Error = ex.Message;
        }
        return results;
    }

Would a good approach here be two break this down into two separate methods? One that sets the request and gets the response like so:

public static SearchResults GetSearchResults(SearchFormModel searchForm, int currentItemCount, int skip)
{
    var results = new SearchResult();
    var client = new RestClient(Settings.Default.SearchWebServiceUrl);
    try
    {
        var request = new RestRequest("{0}", Method.GET);
        if (!searchForm.FirstName.IsNullOrEmpty()){request.AddParameter("forenames",searchForm.FirstName);}
        if (!searchForm.LastName.IsNullOrEmpty()) { request.AddParameter("surname", searchForm.LastName); }

        request.AddUrlSegment("0", "Basic");

        request.AddHeader("Accept", "application/json");

        var response = client.Execute<SearchResult>(request);
        return GetSearchResults(response);
}

Which in turn returns to another method which should be testable ie:

public static SearchResults GetSearchResults(IRestResponse<SearchResults> response)
{
    var results = new SearchResult();
    if (response.ResponseStatus != ResponseStatus.Completed)
        {
            if (response.ErrorException != null)
            {
                SendErrorEmail(response.ErrorException.Message);                        
            }
            throw new Exception(Settings.Default.SearchGenericError);
        }

        if (response.Data != null)
        {
            results.Valid = response.Data.Valid;
            var error = response.Data.Error;
            if (!string.IsNullOrEmpty(error)){error = Settings.Default.SearchGenericError;}
            results.Error = error;
            if (response.Data.SearchResults != null)
            {                        
                results.SearchResults = new List<SearchResult>(response.Data.SearchResults );
            }
        }
        else
        {
            throw new Exception(Settings.Default.SearchGenericError);
        }
    }
    catch (Exception ex)
    {
        registrantList.Error = ex.Message;
    }
    return results;
}

Apologies for the beginner question, however I want to make sure that this approach is the way to go. Would this be the correct way to approach?

Thanks in advance

I basically agree with @unigeek's answer. You will have to break up your classes by responsibility and then use dependency injection (DI) to mock out collaborators. Without this unit testing becomes extremely hard or impossible.

E.g., you wouldn't want a test to actually fire REST requests and send an email. So you have to extract these two responsibilities into their own classes, which you can mock.

Mark Seemann's book on DI greatly helped me to wrap my head around it.

For mocking I like to use NSubstitute, because I find it to be easy to use and lightweight.

Try to take your time and read up on these topics. Unit Testing is hard, but when done right it improves your code quality a lot and makes you a much better developer IMO.

I have a project named A that has a class named ClassA. ClassA has a method named ReadBlock() which creates a CloudBlockBlob object and calls one of its methods.

CloudBlockBlob is a class which is located in Microsoft.WindowsAzure.Storage.Blob namespace which is in Microsoft.WindowsAzure.Storage.dll.

My project A has a unit testing project named A.Tests. Now, I want to test method ReadBlock(). To test it, I need to mock the CloudBlockBlob object and intercept the calls to its methods, return custom values and verify that the methods were called.

  • How can I mock an object that is fully created inside a method?
  • Can I somehow change project A's dll reference and reference it to a mock dll that creates a mock object instead the real one?
  • Can I override project A's call for classes inside the Microsoft.WindowsAzure.Storage.Blob with an implementation of my own in A.Tests class?

UPDATE: The question is whether I can do this without modifying project A's code.

Thanks!

Without modifing class A code you won't be able to UT the ReadBlock method using moq. You'll be able to UT this method using code weaving tools(MsFakes, Typemock Isolator and etc...)

For example(MsFackes):

[TestMethod]
public void TestMethod1()
{
    using (ShimsContext.Create())
    {
        ShimCloudBlockBlob.AllInstances.<the method you want to override>  = (<the method arguments>) => {};
    }
}

In side the using scope you'll be able to override any method CloudBlockBlob has, through the property AllInstances.

In the next section I'm going to discuss all the other options you have...

Option 1:

    public class A
    {
        private IBlockBlob _blockBlob;

        public A(IBlockBlob blockBlob)
        {
            _blockBlob = blockBlob;
        }

        public void ReadBlock()
        {
            _blockBlob.DoSomething();
        }
    }

Since you create a new instance each time call ReadBlock(your method current behavior...), you better inject a factory instead of wrapper and DoSomething should be create; Option 2:

    public class A
    {
        private readonly IFactoryBlockBlob _blobFctory;

        public A(IFactoryBlockBlob blobFctory)
        {
            _blobFctory = blobFctory;
        }

        public void ReadBlock()
        {
           var blob =  _blobFctory.Create();
        }
    }

However based on your question and your comments it seems that your class 'has a dependency' instead of 'need a dependency'.

enter image description here

(Mark Siemens wrote a great book about DI, this chart was taken from his book)

With this new piece of inforamtion you method should be something like; Option 3:

    public class A
    {
        public void ReadBlock(ICloudBlob blob)
        {
        }
    }

But you don't want to change the signeture of the method:

    public class A
    {

        public void ReadBlock()
        {
            ReadBlock(new CloudBlockBlob(<the params bla bla...>));
        }

        internal void ReadBlock(ICloudBlob blob)
        {
        }
    }

Add InternalsVisibleToAttribute, then verify the behavior of the internal method.

By reading between the lines, it feels to me that your class is a kind of "legacy code", by saying "legacy code" I mean class that do the job, won't change and verifying his behavior might be a waste of time. In the past I've posted a chart(in this answer) which may help you to decide the way to handle this case.

I have a Web API application written in C#. I am trying to ensure the design adheres to SOLID principles. As such I am using Unity to inject dependencies into my controllers. However I want to get the actions performed by the controllers out of the controllers themselves, so they essentially just call methods on other (often static) objects. For instance:

public class MyController : ApiController
{
    private readonly ISomeCrossCuttingInterface _instance;
    private readonly ILog _log;

    public MyController(ISomeCrossCuttingInterface someInterface, ILog log)
    {
        _instance = someInterface;
        _log = log;
    }

    [HttpPost]
    [ActionName("MyAction")]
    public RequestResponse MyAction(MyActionData actionData)
    {
        try
        {
            return MyActionUser(actionData);
        }
        catch (Exception ex)
        {
            _log.Error("MyAction error", ex);
        }
        return ...;
    }

    private RequestResponse MyActionUser(MyActionData actionData)
    {
        var responseObj = StaticClass.SomeMethod(_instance, actionData);
        var responseObj2 = StaticClass2.SomeMethod(_instance, responseObj2);
        return CreateMyActionResponse(responseObj2);
    }

    private RequestResponse CreateMyActionResponse(...)
    {
        ...
    }
}

What I am experiencing some angst over is whether the objects used to perform the work (eg. StaticClass and StaticClass2 above) should actually be injected. Currently they aren't. The objects that have been injected are those that are related to cross cutting concerns such as logging or data access, or that are used by more than one controller. So why am I not injecting the objects that perform the work? I am thinking that these 'internal' objects are only used to perform the specific work related to one controller. That is, the controllers functionality has essentially been broken down into objects with a single responsiblity, with each controller having it's own unique set of objects that do whatever the controller needs to do. However is this a bad design? Should all objects be injected regardless? Any input really appreciated.

The only thing you should NOT inject are stable, 3rd party libraries that you know for sure won't change and don't need Testability, Maintainability, Parallel Development, Extensibility or Late Binding.

If the StaticClass actually contains the logic of MyController why not include it's methods as part of StaticClass? Otherwise, it must be doing something else, on another level (different concern).

I'm sure you already have this excellent resource on your shelf, but just to be sure, I'll put a link here: Dependency Injection in .NET (Mark Seemann).

From my own personal experience: If you're actually making a small application, just for the fun of it and which you'll probably throw out when it's done, just have fun with it. Use Dependency Injection here and there, write some Unit Test to see how it feels and get the hang of it. You can't make if perfect. For example, can you easily change between a Console and WPF/WinForms application? What would need to change? How easily can you swap the modules between the two applications? Try writing different ILog implementations. Maybe you want your logs on your console, maybe you want them in some GUI, txt or xml file. How easy is to change your code? Loosely-coupled code is the whole point and the Dependency Injection pattern helps here.

In Mark Seemann's book Dependency Injection in .NET, he states that more people are using DI containers with AUTO-REGISTRATION support where the container can resolve instances of the required concrete types without almost any sort of prior configuration, and this goes well with the convention over configuration architecture approach. but this made me wonder if i used an obfuscator wouldn't this break the code base and cause the container to fail because the conventions have changed ?

You can typically still use dependency injection, even if you ship your application assemblies in an obfuscated way. This will work, because you would typically use generic typing (such as Register<IService, Impl>()) or typeof arguments (such as Register(typeof(IService), typeof(Impl))) to register types. In other words, everything the compiler can check for you will still work (when the obfuscator works correctly).

What you should watch closely is everything the compiler can't check. Things as:

So you will have to watch these issues carefully. Don't forget to safeguard yourself by creating a verifiable configuration and in your case I would verify this configuration on application startup (or add a command line switch so that the application can do a self-check).

In the book Dependency Injection in .NET, the author says that Spring.NET doesn't support creation of custom object lifetimes (See last paragraph of section 12.2 [Managing lifetime]).

Even though I am new to the framework, I think this may not be the case. Based on my research so far, I think one can define custom lifetimes by implementing the ITargetSource interface, though, arguably, this interface can do much more than that (like some predefined implementations include object pooling and hot-swappable targets etc.).

Is my understanding correct? If yes, what are the exact logical steps for creating AND configuring a custom lifetime? If no, how does one create a custom object lifetime in Spring.NET?

Ok, so I actually asked another question here and seems like answered this very question in the process (this is one of those rare occasions where you answer two of your own questions with one answer posted by yourself). If you follow that other question, you'll see that it's indeed possible to define custom life times in Spring.NET.

So in summary, a custom lifetime in Spring.NET can be created by implementing the ITargetSource interface, though, arguably, it's a subtle interface and can be used to do fancy things around creating targets. There are already few implementations available including (but not limited to):

  • SingletonTargetSource (provides the singleton lifetime)
  • PrototypeTargetSource (provides the transient lifetime)
  • ThreadLocalTargetSource (provides thread-scoped lifetime)
  • SimplePoolTargetSource (provides object pooling)
  • HotSwappableTargetSource (provides the capability to swap targets at runtime)

Interestingly, applying a lifetime to your objects can be very different depending on what lifetime you want. All objects in Spring.NET are singleton by default. To specify an object as prototype (Spring.NET speak for transient), you set singleton="false" as follows:

<object id="..." type="..." singleton="false"/>

Unfortunately, there's no such convenient property for the rest of the provided lifetimes (including your custom implementations). So, let's say you want to configure an object with thread-local scope. Here's how you'd do that using ProxyFactoryObject:

<?xml version="1.0" encoding="utf-8"?>
<objects xmlns="http://www.springframework.net">
    <object id="ConsoleLoggingBeforeAdvisor" type="Spring.Aop.Support.DefaultPointcutAdvisor">
        <property name="Advice">
            <object type="Spring.Examples.AopQuickStart.ConsoleLoggingBeforeAdvice"/>
        </property>
    </object>

    <object id="ServiceCommandTargetSource" type="Spring.Aop.Target.ThreadLocalTargetSource">
        <property name="TargetObjectName" value="ServiceCommandTarget"/>
    </object>

    <object id="ServiceCommandTarget" type="Spring.Examples.AopQuickStart.ServiceCommand" singleton="false"/>

    <object name="ServiceCommand" type="Spring.Aop.Framework.ProxyFactoryObject">
        <property name="TargetSource" ref="ServiceCommandTargetSource"/>
        <property name="InterceptorNames">
            <list>
                <value>ConsoleLoggingBeforeAdvisor</value>
            </list>
        </property>
    </object>
</objects>

Again, if you want to achieve the exact same results as the above configuration but using DefaultAdvisorAutoProxyCreator, you'll have to do it in an entirely different way, including implementing a custom type that implements the ITargetSourceCreator interface.

Here's a bare bone ITargetSourceCreator implementation that creates a ThreadLocalTargetSourceCreator:

namespace Spring.Examples.AopQuickStart {
    public class ThreadLocalTargetSourceCreator : AbstractPrototypeTargetSourceCreator, ITargetSourceCreator {
        private readonly ThreadLocalTargetSource _threadLocalTargetSource;

        public ThreadLocalTargetSourceCreator() {
            _threadLocalTargetSource = new ThreadLocalTargetSource();
        }

        protected override AbstractPrototypeTargetSource CreatePrototypeTargetSource(Type objectType, string name, IObjectFactory factory) {
            return _threadLocalTargetSource;
        }
    }
}

Finally, you need to use the following configuration to use the above ITargetSourceCreator with DefaultAdvisorAutoProxyCreator to create instances of your target type at thread-local scope:

<?xml version="1.0" encoding="utf-8"?>
<objects xmlns="http://www.springframework.net" default-autowire="constructor">
    <object id="ConsoleLoggingBeforeAdvice" type="Spring.Aop.Support.DefaultPointcutAdvisor">
        <property name="Advice">
            <object type="Spring.Examples.AopQuickStart.ConsoleLoggingBeforeAdvice" />
        </property>
    </object>

    <object id="ServiceCommand" type="Spring.Examples.AopQuickStart.ServiceCommand" singleton="false"/>

    <object type="Spring.Aop.Framework.AutoProxy.DefaultAdvisorAutoProxyCreator">
        <property name="CustomTargetSourceCreators">
            <list element-type="Spring.Aop.Framework.AutoProxy.ITargetSourceCreator">
                <object type="Spring.Examples.AopQuickStart.ThreadLocalTargetSourceCreator"/>
            </list>
        </property>
    </object>
</objects>

In my opinion, the way you configure lifetimes other than singleton (default) and prototype is somewhat non-intuitive and definitely not streamlined across different types of proxy factory implementations (ProxyFactoryObject vs. DefaultAdvisorAutoProxyCreator)

In summary, yes, Spring.NET does support custom lifetimes. If none of the predefined lifetimes meet your requirements, you can create a custom lifetime by implementing the ITargetSource interface and configuring it appropriately.

It is kind of theoretical question.

I am already using Unity DY with Service(Facade) pattern on Business layer. I is pretty simple to use it but...

there is obviously performance and memory overhead in every small transaction. Instead of creation of DataContext (read it like "sql-connection") i am create several service objects by unity.

Example: simple operation "GetAllArticles" cause creation of

Useless:

  • UserService (for permission checks)
  • ArticleService (for Article Crud operation)

And usefull:

  • DataContext (for the articleService)
  • ArticleViewModels.

But what if is an HightLoadApplication, and billions of people over the world, trying to get article from my super site? What about garbage collector and server's cpu temperature?

So:

  • Am i understand work with unity(or any other) correct?
  • Is there any alternative solutions?
  • what should i do in a case of highload application

I will be happy to hear your opinion and experience, even if it is not panacea or "best practice".

When we write code, we aim for SOLID Design Principals which make code adaptive to change.

  • S : The single responsibility principle
  • O : The open/closed principle
  • L : The Liskov substitution principle
  • I : Interface segregation
  • D : Dependence injection

In order to achieve first four - SOLI, we want to inject dependencies.

Is there any alternative solutions?

You can achieve dependency injection (DI) either manually (Poor Man's Dependency Injection) or using Inversion of Control (IoC) container (like Autofac, Ninject, Structure Map, Unity and so).

what should i do in a case of highload application

Using IoC container for DI is never been an issue for speed.

Mark Seemann said , "creating an object instance is something the .Net Framework does extremely fast. any performance bottleneck your application may have will appear in other place, so don't worry about it."

The bottom line is I personally use IoC container in every ASP.Net MVC and Web API projects. Besides, I hardly see any open source MVC and Web API application which does not use IoC container.

The new place I started at is just starting to develop a completely new product from scratch. They are going transaction script in application services, completely dumb entities, and a hand rolled DAL with stored procedures (the argument is that nhibernate doesn't optimize sql well, loads too much stuff, doesn't scale well to huge projects etc etc etc). the app is supposed to be HUGE project just in it's infancy.

I'm coming from a position where I was doing domain model with all business logic encapsulated in that and the app services only handling infrastructure + loading up the model with nhibernate and scripting it.

I really believe going with the 2nd approach is much better. I was planning on doing a presentation on why. I have plenty of books/articles/personal opinions that I can back this up with...but being more of a "junior" there it might not mean much (I was also the single dev at my last place).

What I'm looking for is some experience/tips/examples of failed projects from more senior people why going transaction script/hand rolled DAL is not the right idea.

In addition to what Paul T Davies and Magnus Backeus have said. I think that at the end of the day it would be a people and cultural issue. If people are open minded and willing to learn it will be relatively easy to convince them. If they consider you a 'junior' (which is a bad sign because the only thing that matters is what you say not how old/experienced you are) you can appeal to a 'higher authority':

Stored procedures are dead and you are not the only one who thinks so:

It is startling to us that we continue to find new systems in 2011 that implement significant business logic in stored procedures. Programming languages commonly used to implement stored procedures lack expressiveness, are difficult to test, and discourage clean modular design. You should only consider stored procedures executing within the database engine in exceptional circumstances, where there is a proven performance issue.

There is no point in convincing people that are not willing to improve and learn. Even if you manage to win one argument and squeeze in NHibernate, for example, they may end up writing the same tightly coupled, untestable, data-or-linq-oriented code as they did before. DDD is hard and it will require changing a lot of assumptions, hurt egos etc. Depending on the size of the company it may be a constant battle that is not worth starting.

Driving Technical Change is the book that might help you to deal with these issues. It includes several behavior stereotypes that you may encounter:

  • The Uninformed
  • The Herd
  • The Cynic
  • The Burned
  • The Time Crunched
  • The Boss
  • The Irrational

Good luck!

I did not find the info by reading the usage guidelines, so I ask my question here: Assuming the following situation:

    /// <summary>
    /// Initalisiert eine neue Instanz des SettingsManager
    /// </summary>
    /// <param name="settingsRepo">Das SettingsRepository welches die Einstellungen enthält</param>
    public SettingsManager(ISettingsRepository settingsRepo)
    {
        Contract.Requires<ArgumentNullException>(settingsRepo != null, "The parameter settingsRepo cant be null");

        _settingsRepo = settingsRepo;
    }

    /// <summary>
    /// Lädt alle Einstellungen
    /// </summary>
    public void Load()
    {
        Contract.Requires<NullReferenceException>(_settingsRepo != null, "The repository cant be null");
        .
        .
        .
    }

where _settingsRepo is a global private field of the class SettingsManager. In the constructor, I define the precondition, that the parameter settingsRepo is not null. So when settingsRepo equals null an Exception is thrown. But the method Load() uses the field _settingsRepo which definetly wasn't null during instantiation. However, I do not know if _settingsRepo equals null at the moment, when Load() is being used, so is the precondition I defined in the method Load() considered as redundant, or should I rest this.

As I mention in the question's comment. You can remove the validation from Load method. The pattern you are using called Constructor Injection. The idea behind C'tor injection is the object you are trying to create needs a dependency and don't have any default/alternative behaviour if you don't supply the dependency. In your case it seem exactly the situation.

Summery: You verified the _settingsRepo is not null in the C'tor, therefore you don't need to verify it again in the Load' method.

This is a very good book about DI, I recommends you to read it.

I'd like to utilize Dependency Injection in ASP.NET MVC 5. The mappings between types and interfaces need to be stored in web.config. Is there anything built-in the ASP.NET MVC 5 for dependency injection from web.config? Or, do I use Unity?

I often think that people are over-eager to define configuration files. Often a programming language makes a straightforward and powerful configuration mechanism. - Martin Fowler

If you are new to Dependency Injection, do not use XML (or web.config) for configuration. XML configuration is a very old technology, and tends to be verbose and brittle.

Instead, you want to use CODE AS CONFIGURATION unless you need late binding. Mainly, you want to use generics and Fluent Builders used by configuration APIs.

Yes, you can use Unity container, if you really want to use XML-centric of DI Container.

You can read more about XML vs Code configuration at Dependency Injection in .NET (Paperback) by Mark Seemann - Page 67.

I have a big class hierarchy. When my app starts, I initialize UnityContainer object and configure it. After that I always passing it through constructors to another classes in hierarchy. Something like this :

Unity container has these classes as Registrations: IClassA, IClassB, IClassC, IClassD

All concrete implementations of interfaces have constructor with IUnityContainer parameter. For example,

    public class ClassA : IClassA
    {

        public ClassA(IUnityContainer unityContainer)
        {
        }
    }

So, every time when I'm creating a new instance of some class I must pass an object of IUnityContainer.

May I reduce amount of passing IUnityContainer object as constructor's parameter? Maybe by using Dependency attribute ?

What you are doing is abusing the container as a ServiceLocator. This is considered an anti-pattern in modern application architecture.

Use proper Dependency Injection instead. Martin Fowler gives a good introduction on the pattern.

Mark Seemann wrote a very good book on the topic called Dependency Injection in .NET.

And as @PeterPorfy already pointed out the concept of Composition Roots is important. You register all dependencies with your container there and then kickoff by resolving the root object of your application or service there.

You never hand the container to a class outside that composition root!

I have a static Configuration class responsible for data settings for my entire system. It loads certain values from the registry in its constructor, and all of its methods are based on these values. If it cannot get the values from the registry (which is possible if the application hasn't been activated yet), it throws an exception, which translates to a TypeInitializationException, which is fine by me.

I wrote unit tests using NUnit to make sure that Configuration's constructor handles all cases correctly - normal values, blank values, Null value. Each test initializes the registry using the relevant values and then calls some method inside Configuration. And here's the problem: NUnit has decided to run the Null test first. It clears the registry, initializes Configuration, throws an exception - all is well. But then, because this is a static class whose constructor just failed - it doesn't re-construct the class again for the other tests, and they all fail.

I would have a problem even without the Null test, because Configuration probably (I'm guessing) gets initialized once for all classes that use it.

My question is: Should I use reflection to re-construct the class for each test, or should I re-design this class to check the registry in a property rather than the constructor?

My advice is to re-design your Configuration class a bit. Because your question is theoretical in nature, with a little practical aspect (failure of unit test), I'll provide some link to back-up my ideas.

First, make Configuration an non-static class. Miško Hevery, engineer at google, has a very good speech about OO Design for Testability where he specifically touches global state as a bad design choice, specially if you want to test it.

Your configuration could accept RegistryProvider instance through constructor (I assume you heard about Dependency Injection principles). RegistryProvider responsibility would be just read values from registry and that's the only thing, that it should do. Now when you test Configuration, you will provide RegistryProvider stub (if you don't know what stubs and mocks are - google it, they are simple in nature), where you will hardcode values for specific registry entries.

Now, benefits:

  • you have good unit tests, because you don't rely on registry
  • you don't have global state (testability)
  • your tests don't depend on each other (each have separate Configuration instance)
  • your tests don't rely on environment, in which they are executed (you may not have permissions to access registry, but still you are able to test your Configuration class)

If you feel like you are not quite good at Dependency Injection, I would recommend a marvelous piece of art and engineering, provided to mortal souls by the genius of Mark Seemann, called Dependency Injection in .NET. One of the best book I've read about class design, which is oriented to .NET developers.

To make my answer more concrete :

Should I use reflection to re-construct the class for each test?

No, you should never use reflexion in your tests (only if it is no other case). Reflexion will make you tests:

  • fragile
  • hard to understand
  • hard to maintain

Use object-oriented practices with conjunction of encapsulation to achieve hiding of implementation. Then test only external behavior and don't rely on internal implementation details. This will make you tests depend only on external behavior and not on internal implementation, which can change a lot.

should I re-design this class to check the registry in a property rather than the constructor?

Designing you class as described in my answer will make you able to test your class not accessing registry at all. This is a cornerstone of unit tests - not to rely on external systems (databases, file systems, web, registry, etc... ). If you want to test if you can access registry at all - write separate integration tests, where you will write to registry and read from it.

Now I don't have enough information to tell you whether you should read registry via RegistryProvider in Configuration constructor, or lazily read registry on demand, that's a tricky question. But I definitely can say - try to avoid global state as much as you can, try to minimize dependency on implementation details in you tests (this related to OO principles as a whole) and try to tests you objects in isolation, i.e. without accessing external systems. Then you can mimic exceptional cases, for example does you class behaves as expected when registry is no available? It is really hard to re-create such scenario if you access registry directly via static members of a Configuration class.

I'm a C# programmer and I'm thinking about dependency injection. I've read "Dependency injection in .NET" book and patterns and antipatterns of DI are quite clear for me. I use pattern injection in constructor most of the time. Are there any cases in wich it is preferrable to create instances directly rather than using a Dependency Injection framework?

Using Dependency Injection has the advantage of making code Testable, however abusing DI pattern makes code harder to understand. Take in example this framework (ouzel, I'm not affiliated in any way. I just liked the way it was designed) wich I started recently to follow, as you see most classes have dependencies injected, however there is still a single instance shared without constructor injection sharedEngine.

In that particular case I find the author did a good choice, that makes the code overall simpler to understand (simpler constructors, less members) and eventually more performant (you don't have a shared pointer stored in every instance of every class of the engine).

Still its code can be tested because you can replace that instance (global) with a mock (the worst point of globals is that initialization order and their dependencies are hard to track, however if you limit to few globals with no or few dependencies this is not a problem). As you see you are not always forced to inject everything from constructor (and I wrote a DI injection framework for C++).

The problem is that people think is always good injectin everything from constructor so you suddendly start seeing frameworks that allow to inject everything (like int or std::vector<float>) while in reality that's the worst idea ever (infact in my simple framework I allow just to inject classes) since code becomes harder to understand because you are mixing configuration values with logic configuration and you have to travel through more files to get a grasp of what code is doing.

So, constructor injection is very good, use it when it is proper, but it is not the Jack-of-all-trades like everything in programming you have to not abuse it. Best of all try to understand good examples of every programming practice/pattern and then roll your own recipe, programming is made of choices, and every choice have good and bad sides.

When is it Ok (and by "OK" I mean you will still be able to test the code, as it were not coupled to concrete instances) to call "new":

  • You need Polymorphis, most times it is easier to create the new class than configuring that using a DI framework
  • You need a object factory, usually the factory itself is injected, however the factory code call "new" explicitly
  • You are calling "new" in the main
  • The object you are creating with "new" has no dependencies, and thus using it inside a class does not make the class harder to test (in example you create standard .NET containers with new, doing otherwise results in much more confusion)
  • The object you are creating is a global instance wich do not rely on order of initialization and its dependencies are not visible otherelse (you can mock the instance as long as you access it through a interface).

The above list provide situations in wich even when using a DI framework (like Ninject) it is ok to call "new" without removing the possibility to test your code, even better, most times you use DI in the above cases you usually end up with more complex code.

I'm using Autofac in ASP.Net WebForm. According to the documentation, if I want to resolve dependencies in web controls, I'll need to use the following approach -

Dependency Injection via Base Page Class

public class MyWebControl : WebControl
{
   public IFirstService FirstService { get; set; }
   public ISecondService SecondService { get; set; }

   public MyWebControl()
   {        
      var cpa = (IContainerProviderAccessor)
           HttpContext.Current.ApplicationInstance;
      var cp = cpa.ContainerProvider;
      cp.RequestLifetime.InjectProperties(this);
   }
}

The above code work fine. However, in order to improve the speed, I'm thinking that I can resolve depedencies myself using the following approach.

public MyWebControl()
{        
   var cpa = (IContainerProviderAccessor)HttpContext.Current.ApplicationInstance;
   var cp = cpa.ContainerProvider;
   FirstService = cp.ApplicationContainer.Resolve<IFirstService>();
   SecondService = cp.ApplicationContainer.Resolve<ISecondService>();
}

Please correct me if I'm wrong. I doubt that it is a Service Locator pattern (Mark Seemann said Service Locator is an Anti-Pattern in Dependency Injection in .NET book).

Question

Should I use the first approach or second?

I'd say use the first approach. The least knowledge your code has on the actual container the better. You should only care about your dependencies.

I'm writing unit tests for view models. The app is written using Caliburn.Micro for MVVM support. Many view models depend on Application.Current.Dispatcher with intention to dispatch some code into the UI thread.

To create the Application object from within the tests I have written the following class:

public class AppInitializer {
    private static Application app;
    public static void InitApp() {
        app = app ?? (app = Application.Current ?? new Application());
    }
}

Now I just do the following in each test class:

[ClassInitialize]
    public static void InitClass(TestContext ctx) {
        AppInitializer.InitApp();
    }

Unfortunately, the first call to Application.Current.Dispatcher from within a view model hangs my tests until timeout will be reached.

I don't want to abstract somehow the Application.CurrentDispatcher, I don't want to pass into view models one more mocked object. I want to get some workaround if this is possible.

I think you are missing the call to Application.Run. You're right that one of the Application classes' responsibilities is to create and start a Dispatcher on the thread that it is currently executing on but all this happens during the call to Run.

And this is where the trouble begins: Run is a blocking call, i.e. your unit tests will not be executed until Run exits. In Store Apps, there is a special attribute called UITestMethod but I don't think that it is available in WPF (especially if you are not using MSTest).

So what are your options? You could create the application on a different thread than the one your unit tests run on - but this will result in method calls to Join as you have to look if your call was dispatched to the other thread. This is potential for slow unit tests.

You even cannot create a dispatcher manually on the thread your unit tests are executed on - because it is the same thing as mentioned before with the App class: Dispatcher.Run is a blocking call.

That's why I would advise you to create an abstraction for Dispatcher and inject it - it's saves you a lot of pain.

Update for Ambient Context:

In the comments, I mentioned the Ambient Context as a solution that does not rely on injecting an object into view models that conforms to the Dispatcher abstraction. This is how it would look like in code:

public interface IDispatcher
{
    void ExecuteOnUIThread(Action action);
    // Add whatever methods you need on this interface
}

public static class DispatcherContext
{
    // An instance that implements IDispatcher can be accessed via this static property
    public static IDispatcher Dispatcher { get; set; }
}

// Of course you need to write an adapter for the WPF Dispatcher class

This way you can create a dispatcher mock for your unit tests but still be able to access this via a static property in your view models. You can learn more about this pattern on http://blogs.msdn.com/b/ploeh/archive/2007/07/23/ambientcontext.aspx or in Mark Seemann's excellent book Dependency Injection in .NET.

In my mid-size project I used static classes for repositories, services etc. and it actually worked very well, even if the most of programmers will expect the opposite. My codebase was very compact, clean and easy to understand. Now I tried to rewrite everything and use IoC (Invertion of Control) and I was absolutely disappointed. I have to manually initialize dozen of dependencies in every class, controller etc., add more projects for interfaces and so on. I really don't see any benefits in my project and it seems that it causes more problems than solves. I found the following drawbacks in IoC/DI:

  • much bigger codesize
  • ravioli-code instead of spaghetti-code
  • slower performance, need to initialize all dependencies in constructor even if the method I want to call has only one dependency
  • harder to understand when no IDE is used
  • some errors are pushed to run-time
  • adding additional dependency (DI framework itself)
  • new staff have to learn DI first in order to work with it
  • a lot of boilerplate code, which is bad for creative people (for example copy instances from constructor to properties...)

We do not test the entire codebase, but only certain methods and use real database. So, should Dependency Injection be avoided when no mocking is required for testing?

Was there a reason why you didn't choose to use an IOC Library (StructureMap, Ninject, Autofac, etc)? Using any of these would have made your life much easier.

Although David L has already made an excellent set of commentaries on your points, I'll add my own as well.

Much bigger codesize

I am not sure how you ended up with a larger codebase; the typical setup for an IOC library is pretty small, and since you are defining your invariants (dependencies) in the class constructors, you are also removing some code (i.e. the "new xyz()" stuff) that you don't need any more.

Ravioli-code instead of spaghetti-code

I happen to quite like ravioli :)

Slower performance, need to initialize all dependencies in constructor even if the method I want to call has only one dependency

If you are doing this then you are not really using Dependency Injection at all. You should be receiving ready-made, fully loaded object graphs via the dependency arguments declared in the constructor parameters of the class itself - not creating them in the constructor! Most modern IOC libraries are ridiculously fast, and will never, ever be a performance problem. Here's a good video that proves the point.

Harder to understand when no IDE is used

That's true, but it also means you can take the opportunity to think in terms of abstractions. So for example, you can look at a piece of code

public class Something
{
    readonly IFrobber _frobber;
    public Something(IFrobber frobber)
    {
        _frobber=frobber;
    }

    public void LetsFrobSomething(Thing theThing)
    {
        _frobber.Frob(theThing)
    }
}

When you are looking at this code and trying to figure out if it works, or if it is the root cause of a problem, you can ignore the actual IFrobber implementation; it just represents the abstract capability to Frob something, and you don't need to mentally carry along how any particular Frobber might do its work. you can focus on making sure that this class does what it's supposed to - namely, delegating some work to a Frobber of some kind.

Note also that you don't even need to use interfaces here; you can go ahead and inject concrete implementations as well. However that tends to violate the Dependency Inversion principle (which is only tangenitally related to the DI we are talking about here) because it forces the class to depend on a concretion as opposed to an abstraction.

Some errors are pushed to run-time

No more or less than they would be with manually constructing graphs in the constructor;

Adding additional dependency (DI framework itself)

That is also true, but most IOC libraries are pretty small and unobtrusive, and at some point you have to decide if the tradeoff of having a slightly larger production artifact is worth it (it really is)

New staff have to learn DI first in order to work with it

That isn't really any different than would be the case with any new technology :) Learning to use an IOC library tends to open the mind to other possibilities like TDD, the SOLID principles and so forth, which is never a bad thing!

A lot of boilerplate code, which is bad for creative people (for example copy instances from constructor to properties...)

I don't understand this one, how you might end up with much boilerplate code; I wouldn't count storing the given dependencies in private readonly members as boilerplate worth talking about - bearing in mind that if you have more than 3 or 4 dependencies per class you are likely to be in violation of the SRP and should rethink your design.

Finally if you are not convinced by any of the arguments put forth here, I would still recommend you read Mark Seeman's "Dependency Injection in .Net". (or indeed anything else he has to say on DI which you can find on his blog). I promise you will learn some useful things and I can tell you, it changed the way I write software for the better.

My development team is evaluating the various frameworks available for .NET to simplify our programming, one of which is CSLA. I have to admit to being a bit confused as to whether or not CSLA would benefit from being used in conjunction with a dependency injection framework, such as Spring.net or Windsor. If we combined one of those two DI frameworks with, say, the Entity Framework to handle ORM duties, does that negate the need or benefit of using CSLA altogether?

I have various levels of understanding of all these frameworks, and I'm trying to get a big picture of what will best benefit our enterprise architecture and object design.

Thank you!

Short answer: Yes.

Long answer: It requires a bit of grunt work and some experimentation to setup, but it can be done without fundamentally breaking CSLA. I put together a working prototype using StructureMap and the repository pattern and used the BuildUp method of Setter Injection to inject within CSLA. I used a method similar to the one found here to ensure that my business objects are re-injected when the objects are serialized.

I also use the registry base class of StructureMap to separate my configuration into presentation, CSLA client, CSLA server, and CSLA global settings. This way I can use the linked file feature of Visual Studio to include the CSLA server and CSLA global configuration files within the server-side Data Portal and the configuration will always be the same in both places. This was to ensure I can still change the Data Portal configuration settings in CSLA from 2 tier to 3 tier without breaking anything.

Anyway, I am still weighing the potential benefits with the drawbacks to using DI, but so far I am leaning in the direction of using it because testing will be much easier although I am skeptical of trying to use any of the advanced features of DI such as interception. I recommend reading the book Dependency Injection in .NET by Mark Seemann to understand the right and wrong way to use DI because there is a lot of misinformation on the Internet.

EDIT: I just realized that what I want to do follows the Dependency Injection pattern that I learned from Mark Seemann who wrote an excellent book on the subject. I want to have a method where I do some setup, like adding rows, but pass in an object that writes the rows to the context. The BulkInsert method is for large "setups" and the AddRange is for smaller setups.

I have a static method where I'm passing in my DbContext, and I'm updating rows to several entities. Depending on how I call the method, I want to either add the rows using BulkInsert or AddRange

public static void MySetup(MyContext, int addMethod)
{
    var list1 = new List<Foo>{......}
    if (addMethod = 1)
       context.BulkInsert(list1);
    else
       context.AddRange(list1);

    var list2 = new List<Bar>{......}
    if (addMethod = 1)
       context.BulkInsert(list2);
    else
       context.AddRange(list2);

}

Instead of passing in a variable, I'd like to learn how I can pass in a function instead, so it would like something like this:

public static void MySetup(MyContext context, ??? myAdd)
{
    var list1 = new List<Foo>{......}
    myAdd(context, list1);

    var list2 = new List<Bar>{......}
    myAdd(context, list2);
}

I think what I'm looking for is a delegate. Note that I use different types of List classes, so whatever functions I setup on the calling end would need to accept a generic list (is that ?) because I wouldnt want to have to pass in a function for every possible type.

ETA:

BulkInsert and AddRange are both adding rows via EntityFramework. And they each take a List. However BulkInsert has an optional options parameter so it may be called like context.BulkInsert(myList, opts)

I am about to start a new WPF project with PRISM 4.1 (and Reactive UI). Now, I am bit unsure about the IOC/DI bit. I've played around with MEF and Structure Map and so far I really like MEF and its extensibility feature.

The problem is so far I've always use Structure Map as my IOC/DI and to help me with unit test (I use MOQ for mocking).

Is it recommended to use MEF as DI/IOC? Or should I stick with Structure Map for my IOC/DI, and just use MEF in WPF?

That depends on your needs for the IOC, but it is possible to use MEF as your IOC.

Glenn Block has a blog post about this from 2009.

http://codebetter.com/glennblock/2009/08/16/should-i-use-mef-for-my-general-ioc-needs/

Mark Seeman has a chapter on MEF as IOC in his book.

http://www.amazon.com/Dependency-Injection-NET-Mark-Seemann/dp/1935182501/ref=sr_1_1?ie=UTF8&qid=1332021360&sr=8-1

I am creating a MVC application using NINject as my IOC. I am trying to separate my business logic from controller. And so I don't want my controller constructor creates for my any Dependency Object i.e. I dont want to pass my interface in the constructor and than it gets resolved through IOC container. It should be the responsibility of the business logic layer. I am trying to achieve something like below.

public BusinessHolidayController()
{

}
// GET: BusinessHoliday
public ActionResult Index(Product product)
{
    string model = invoke<IProduct>().GetSum(product);
    return View(model);
}

What you are above to do is leaning toward Service Locator Pattern which is anti-pattern and a dangerous pattern. Its disadvantages are greater than its advantages.

There are four basic DI patterns -

  1. Constructor Injection
  2. Property Injection
  3. Method Injecton
  4. Ambient Context

For MVC controller, you want to use Constructor Injection, because it is the best pattern of the above four patterns especially for controller.

It should be the responsibility of the business logic layer.

No. Composite Root should be placed entry point of the application such as Global.asax.

For more information, you want to read Mark Seemann's Dependency Injection in .NET.

I didn't understand that in all examples of IOC i could find, one interface can only have one implemented class in the dictionary of class mapping. Whatever DI or Service locator

It's a little bit stupid in my mind, no?

All the DI Containers I walk through in my book support multiple registrations of the same interface:

Castle Windsor

container.Register(Component
    .For<IIngredient>()
    .ImplementedBy<Steak>());
container.Register(Component
    .For<IIngredient>()
    .ImplementedBy<SauceBéarnaise>());

Autofac

builder.RegisterType<SauceBéarnaise>().As<IIngredient>();
builder.RegisterType<Steak>().As<IIngredient>();

Unity

container.RegisterType<IIngredient, Steak>();
container.RegisterType<IIngredient, SauceBéarnaise>("sauce");

There are more containers that support this; these are only examples. My book contains much more detailed examples.

I have the following method:

Void UpdateUser(User user){}

I need to check this method whether will work properly.

I've used a separate db to check this in unit testing. But many experienced people said if I use this method that won't be unit testing; that's integration testing.

But I don't know how to mock for unit testing.

The code written in the UpdateUser method, will try to update data using Entity framework.

If I mock (Actually I don't how to do this either), how this will work with entity framework?

Mocking means that you develop your software components (classes) in a way that any class with behaviour is used/consumed/called-upon as an interface (or abstract class). You program to an abstraction. Run-time you use something (service locator, DI container, factory, ...) to retrieve/create those instances.

The most common way is to use construction injection. Here is an excellent explanation of why one would use DI, and examples of how to do it.

In your case, your component that uses the Entity Framework (your repository for instance) must implement a repository-interface, and any class that uses your repository should use it as an interface.

This way, you can mock the repository in your unittests. Which means that you create a unit-test-repository class (which has nothing to do with any database or EF), and use that when you create the instance of the class that you want to unit-test.

Hopefully this helps. There are many source to be found. Personally I just read this book and I found it to be very good. This is the authors blog.

I'm dealing with one problem. Imagine this example situation. I have one module e.g. UserModule with injected IUserRepository. IUserRepository can have more implementations e.g. IUserRepositorySql and IUserRepositoryDefault.

public class UserModule : IUserModule
{
    private readonly IUserRepository userRepository;

    public UserModule(IUserRepository userRepository)
    {
        if (userRepository == null) throw new ArgumentNullException("userRepository");
        this.userRepository = userRepository;
    }
}

I would like to define which implementation of IUserRepository will be used in UserModule. I want to avoid Factory pattern that is considered like IoC antipattern in Marc Seeman book and I would like achieve this only with container configuration.

I'm using LightInject and it has something like named services but it can be used only on the top level. I need something like this :

var container = new ServiceContainer();

container.Register<IUserRepository, UserRepositorySql>("Sql");
container.Register<IUserRepository, UserRepositoryDefault>("Default");
container.Register<IUserModule, UserModule>();

var instance = container.GetInstance<IUserModule>("Sql");

This code should return instance of IUserModule with injected UserRepositorySql instance, but of course, it doesn't.

Do you have some soulution for this in LightInject please?

I found a feature annotation in Lightinject where I can inject some properties of an appropriate types, but I don't like this solution so much.

Do you have any experience in some other IoC containers? How do you/which feature does solve this issue?

I would have to agree both with Steven and Astrotrain here, but there is a third option available.

The following example uses parameters to resolve the correct implementation of the IUserRepository interface.

using LightInject;

class Program
{
    static void Main(string[] args)
    {
        var container = new ServiceContainer();
        container.Register<IUserRepository, UserRepositorySql>("Sql");
        container.Register<IUserRepository, UserRepositoryDefault>("Default");
        container.Register<string, IUserModule>(
            (factory, serviceName) => new UserModule(factory.GetInstance<IUserRepository>(serviceName)));

        var userModuleWithSqlRepository = container.GetInstance<string, IUserModule>("Sql");
        var userModuleWithDefaultRepository = container.GetInstance<string, IUserModule>("Default");
    }
}

public interface IUserModule { }

public class UserModule : IUserModule
{
    public UserModule(IUserRepository repository)
    {
    }
}

public interface IUserRepository { }

public class UserRepositorySql : IUserRepository { }

public class UserRepositoryDefault : IUserRepository { }

I'm making a map loading system that uses chunks so that the entire map data doesn't have to be loaded at once.

I have a "World" class, and within that class I'm creating an instance of a class called "ChunkManager".

I'm unsure if creating an instance inside another class is a good idea/considered a "normal" thing to do etc. I've not been able to find anything about this while searching the internet.

So my question is: Should I be creating an instance of a class within a class in the way I have, or will there be problems with doing it this way?

Here is my code, if it's relevant:

class World
{

    public string WorldName { get; set; }
    ChunkManager chunkManager = new ChunkManager();


    public World(string worldName)
    {
        WorldName = worldName;

    }

    public void AddChunk(int X, int Y)
    {
        //Plus other validation code here that I didn't paste
        chunkManager.AddChunk(X, Y);
    }
}

And ChunkManager:

class ChunkManager
{
    public int TotalGeneratedChunks { get; private set; }

    private List<Chunk> ChunkList = new List<Chunk>();

    public bool CheckIDExists(int IDToCheck)
    {
        foreach (Chunk i in ChunkList)
        {
            if (i.UniqueID == IDToCheck)
            {
                return true;
            }
        }

        return false;
    }

    public void AddChunk(int X, int Y)
    {
        ChunkList.Add(new Chunk(TotalGeneratedChunks++, X, Y));

    }
}

It's perfectly fine to create an instance of a class inside another. chunkManager is what is known as a field and the syntax for initializing it inline along with its declaration is called an initializer. You can find more information on initializers and how they are different from initializing via the constructor in this blog series by Eric Lippert

Part 1 Part 2

It might some times be a better idea to initialize fields via the constructor though as this lets you use dependency injection (parameter injection to be precise) which can greatly improve the testability and modularity of your code. If you're interested in learning more about dependency injection I suggest purchasing and reading this book.

I've got some code as shown below with multiple methods which call a web service to get some data from a database. This will produce a set of fields which are then added to another database from the web app. This all works great but I have no idea how to unit test any of it due to it mostly outputting voids, and the data coming from a database which changes every time the button is clicked. Is there a way to unit test to just if the methods work or not? Sorry I am very new to unit testing but I know how important it is so any help would be appreciated.

    //Get webservice service
    private Service1 GetService()
    {
        return new TestProjectService.Service1();
    }

    //Choose which webservice we want to use based on radio button selection
    private TestProjectService.CommandMessages GetCommand(Service1 service)
    {
        var command = new TestProjectService.CommandMessages();

        switch (WebServiceRadio.SelectedIndex)
        {
            case 0:
                command = service.GetData();
                break;
            case 1:
                command = service.GetDataLINQ();
                break;
        }

        return command;
    }

    //Display the results in a label on screen
    private void DisplayResult(string text)
    {
        LatestCommandLabel.Text = text;
    }

    //Get the current username of the user logged in
    public string GetUsername()
    {
        return System.Security.Principal.WindowsIdentity.GetCurrent().Name;
    }

    //Submit the data to the database using Linq
    private void SubmitData(string username, TestProjectService.CommandMessages command)
    {
        var dc = new TestProjectLinqSQLDataContext();

        var msg = new TestProjectCommandMessage
        {
            Command_Type = command.CommandType,
            Command = command.Command,
            DateTimeSent = command.DateTimeSent,
            DateTimeCreated = command.DateTimeCreated,
            Created_User = username,
            Created_Dttm = DateTime.Now
        };

        dc.TestProjectCommandMessages.InsertOnSubmit(msg);
        dc.SubmitChanges();
    }

    //Return the value and submit data to database
    private void ReturnValue()
    {
        var service = GetService();
        var command = GetCommand(service);
        var username = GetUsername();

        if (command != null)
        {
            DisplayResult(String.Format("Last Command Called (Using {0}) : {1}", WebServiceRadio.SelectedItem.ToString(), command.Command));
            string userName = GetUsername();
            SubmitData(username, command);
        }
        else
        {
            DisplayResult("No Commands Available");
        }
    }

    //Onlick return value
    protected void GetCommandButton_Click(object sender, EventArgs e)
    {
        ReturnValue();
    }

Behavior verification is the approach used to test methods that don't return any values.

In a nutshell, since the method doesn't return any results, the only thing a test can do is make sure the method causes the appropriate actions to take place. This is typically accomplished by using a mock object, which keeps track of whether or not its methods have been called.

In order for your tests to use test doubles, you need to include seams in the design of your system.

I strongly recommend reading Dependency Injection in .Net, by Mark Seeman. Since you're new to unit testing, you undoubtedly have many questions on the mechanics involved in unit testing (and this answer probably sparked even more questions) - this book goes into great detail answering those questions.

So from this post I got the following code for passing command line arguments into my WPF Application

public partial class App : Application
{
    private string _customerCode;
    public string CustomerCode
    {
        get { return _customerCode; }
        set { _customerCode = value; }
    }


    protected override void OnStartup(StartupEventArgs e)
    {
        if (e.Args.Count() != 0)
        {
            CustomerCode = e.Args[0].Replace("/", string.Empty); 
        }
    }
}

The application then starts my MainWindow.xaml and the application runs but in the viewModel for MainWindow.xaml (MainViewModel.cs) I would like to access the value of App.CustomerCode.

Is this the right way to deal with command line arguments and is it possible to access the value of CustomerCode?

One of the easy ways to access the customer code is to overwrite the Application.Current property with the new keyword (as more or less Davut has pointed out in his answer):

public class App : Application
{
    public static new App Current
    {
        get { return (App) Application.Current; }
    }

    public string CustomerCode { get; set; }
    protected override void OnStartup(StartupEventArgs e)
    {
        this.CustomerCode = e.Args[0].Replace("/", string.Empty);
        base.OnStartup(e);
    }
}

In your view model you can then access the customer code by writing App.Current.CustomerCode.

However, if you want a more object-oriented way regarding the SOLID principles, I would advise to do the following: in your OnStartup method, create the view model and the main window in code and show it. Using this approach, you can inject the customer code to the view model, e.g. via constructor injection. The OnStartup method would look like this:

protected override void OnStartup(StartupEventArgs e)
{
    base.OnStartup(e);

    // Composition root
    var customerCode = e.Args[0].Replace("/", string.Empty);

    // Here I inject the customer code to the view model so that 
    // it can save it in a field and use it later.
    // This is called dependency injection (here it's constructor injection)
    var mainWindowViewModel = new MainWindowViewModel(customerCode);
    MainWindow = new MainWindow { DataContext = mainWindowViewModel };
    MainWindow.Show();
}

For this to work, you have to remove the StartupUri entry in App.xaml - otherwise your manually created main window will not show up.

Your view model would look like this:

public class MainWindowViewModel
{
    private readonly string _customerCode;

    public MainWindowViewModel(string customerCode)
    {
        if (customerCode == null)
            throw new ArgumentNullException("customerCode");

        _customerCode = customerCode;
    }

    // Other code in this class can access the _customerCode field
    // to retrieve the value from the command line
}

This approach is a more flexible than to access the static App.Current property as your view model is independent of the App class (i.e. it has no references to it).

If you want to learn more about dependency injection, just google it, you'll find plenty of example. I can also recommend the excellent book Dependency Injection in .NET by Mark Seemann, if you want to dive in more.

There are many IOC containers for .net out there mainly MEF, Spring.net, Castle Windsor, Unity etc. Which is the most extensible and high performant? What should one consider when choosing a particular IOC container?

Thanks in adv

I think that reading the book "Dependency Injection in .NET" by Mark Seemann is the best way. Mark goes through several containers and is very good at all of them. http://www.amazon.com/Dependency-Injection-NET-Mark-Seemann/dp/1935182501/ref=sr_1_1?ie=UTF8&qid=1326500032&sr=8-1

I don't think that IOCBattle.com tells someone enough about real world use and best practices to rule out Ninject and Castle because they were much slower according to the results by MartinF who is the author of a little known IOC container.

Ninject is very easy to use and is in the Apress MVC 3 book. Unity is becoming popular as it is from Microsoft, and StructureMap is pretty nice (and has been favorable to many developers). They seem to perform pretty well. Unless someone with a heavy hit site has exposure to bench marking performance on each container or has done performance and load testing with concurrent users with a tool like JMeter.

I don't think some of these benchmarks accurately reflect the product. If your company must use the Microsoft stack, then hands down you must use Unity ( MEF lacks too many features for most situations). If you are "allowed" to use 3rd party / open source, then StructureMap, Ninject, Castle, and Autofac are the most popular. Again, Mark's book on DI has charts that break down which ones have auto-registration, xml configuration, lifetime.., this stuff becomes pretty important for an application.

We have an ASP.NET Web Forms solution we made a few years ago. This solution had the following layers:

  • Data Access layer: where we had the access to the data, just a few procedures like this one

    public void execute_NonQuery_sql(string SQL) {...}

  • Data Entities: in this layer we defined the different entities and the queries to access the database.

    public static DataTable sel_links()
    {
        mySQL_DA da = new mySQL_DA();
        string sQuery = "SELECT Id, Name, WebSite, Summary FROM links ORDER BY OrderPos ASC";
        return da.get_DataTable_sql(sQuery);
    }
    
  • Data Logic: where we call the procedures and return the objects.

    public List<LinksDN> sel_links_web()
    {
        try
        {
            using (DataTable dt = LinksDA.sel_links_web())
            {
                List<LinksDN> ListElements = new List<LinksDN>();
    
                foreach (DataRow dr in dt.Rows)
                {
                    LinksDN Element = new LinksDN(dr);
                    ListElements.Add(Element);
                }
    
                return ListElements;
            }
        }
        catch (Exception e)
        {
            throw e;
        }
    }
    
  • Presentation layer: where we had the web pages. We called all the procedures in the logic layer.

Now we are developing a similar application but we'd like to use Entity Framework and Model Binding. We are developing using Visual Studio 2013 Web Forms Framework 4.5.

We wrote a lot of code in the past but now we see is easier since we don't have to write that much of code thanks to EF.

But still we have a few questions:

1) How can we structure the application? Do we need to create different projects as layers?

We have seen that we don't need to have procedures to access the data since EF takes care of that. So would it be enough with 2 layers, one for the Model and another one for the business logic (and the presentation layer, of course)?

2) When you use EF, do you have to dispose the DbContext? We have seen this example, is the correct?

public class LinksBL
{
    ObjectDbContext db = new ObjectDbContext();

    public List<links> GetLinks()
    {
        return db.links;
    }

    public List<links> GetLinks()
    {
        return db.links;
    }

    public links GetLink([QueryString("id")]int? LinkId)
    {
        return db.links.Find(LinkId);
    }
}

3) Also, if the entity Links (for example) has a lot of properties, do you always return all the properties even is you don't use them?

It can happen we have a list where we just need 3 properties and another list where we need all of them. Do we have to create 2 different procedures, one for each, and return only the properties we are going to use? If yes, how can we return just a few properties?

Questions might be too obvious, but we used to develop different way and EF is new for us. Thanks for helping.

1) How can we structure the application? Do we need to create different projects as layers?

If you ask 10 people, they will answer 10 different answers.

Look at open source project such as NopCommerce, Orchard or Umbraco. (They are all MVC; it is hard to find Web Form project these days).

Recently, I read ASP.NET Web API 2: Building a REST Service from Start to Finish. It explains how to create project structure step-by-step. (Although it is written for Web API, you will get the idea of how projects are layout.) Here is the source code.

2) When you use EF, do you have to dispose the DbContext? We have seen this example, is the correct?

You do not want to instantiate DbContext inside service classes. Instead, you want to inject dependencies using IoC container.

In addition, you do not want to call HttpContext object inside Database layer like you did in the method parameter.

FYI: you situation is very similar to Dependency Injection in .NET book Chapter 2. In the book, Mark Seemann explains the problem of tight coupling, and how to solve using dependency injection.

3) Also, if the entity Links (for example) has a lot of properties, do you always return all the properties even is you don't use them?

Some people like to return IQueryable from service classes instead of IList or custom collection. If IQueryable, you can retrieve only the properties that you want.

Other thoughts

If it is a new project, I would like to suggest to use ASP.Net MVC instead of Web Form. The reason is you cannot unit test Web Form, and it is hard to inject dependencies in Web Form.

Updated: 10/8/2014

we have been developing using WebForms and the application is quite complex

I see. However, layers of class libraries are basically same; only presentation layer is different. Main concept is you should be able to add Web Form, WPF, MVC, Web API to your existing solution without changing anything in class libraries. In order to do that you need to inject dependencies instead of tight coupling (you can still implement dependency injection in Web Form).

On thing I forget to mention is you want to access DbContext via Repository. In other words, Service layer should not need to know what kind of database you are using.

Look at those open source projects in answers 1.

Writing unit tests that require database access via my CustomMembershipProvider.

edit -

 public class CustomMembershipProvider : MembershipProvider
    {
         public override bool ValidateUser(string username, string password)
        {

            using (var usersContext = new UsersContext())
            {
                var requiredUser = usersContext.GetUser(username, password);
                var userApproved = usersContext.GetUserMem(username);
                if (userApproved == null) return false;
                return (requiredUser != null && userApproved.IsApproved != false);
            }
        }
    }

   [TestFixture]
    public class AccountControllerTest
    {

        [Test]
        public void ShouldNotAcceptInvalidUser()
        {
            // OPTION1
            Mock<IMembershipService> membership = new Mock<IMembershipService>();
            //OPTION2
            // Mock<AccountMembershipService> membership = new Mock<AccountMembershipService>();

            membership.Setup(m => m.ValidateUser(It.IsAny<string>(), It.IsAny<string>()))
                      .Returns(false);
            var logonModel = new LoginModel() { EmailorUserName = "connorgerv", Password = "pasdsword1" };
            var controller = new AccountController(membership.Object);

            // Act
            var result = controller.Login(logonModel,"Index") as RedirectResult;

            // Assert
            Assert.That(result.Url, Is.EqualTo("Index"));
            Assert.False(controller.ModelState.IsValid);
            Assert.That(controller.ModelState[""],
                        Is.EqualTo("The user name or password provided is incorrect."));
        }

        [Test]
        public void ExampleForMockingAccountMembershipService()
        {
            var validUserName = "connorgerv";
            var validPassword = "passwordd1";
            var stubService = new Mock<CustomMembershipProvider>();
            bool val = false;

            stubService.Setup(x => x.ValidateUser(validUserName, validPassword)).Returns(true);

            Assert.IsTrue(stubService.Object.ValidateUser(validUserName, validPassword));
        }

    }



public class AccountController : Controller
    {
        public IMembershipService MembershipService { get; set; }

        public AccountController(IMembershipService service){

            MembershipService=service;
        }

        protected override void Initialize(RequestContext requestContext)
        {
            if (MembershipService == null) { MembershipService = new AccountMembershipService(); }

            base.Initialize(requestContext);
        }

        public ActionResult Index()
        {
            return RedirectToAction("Profile");
        }


        public ActionResult Login()
        {
            if (User.Identity.IsAuthenticated)
            {
                //redirect to some other page
                return RedirectToAction("Index", "Home");
            }
            return View();
        }

        //
        // POST: /Account/Login

        [HttpPost]
        public ActionResult Login(LoginModel model, string ReturnUrl)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ValidateUser(model.EmailorUserName, model.Password))
                {

                    SetupFormsAuthTicket(model.EmailorUserName, model.RememberMe);

                    if (Url.IsLocalUrl(ReturnUrl) && ReturnUrl.Length > 1 && ReturnUrl.StartsWith("/")
                        && !ReturnUrl.StartsWith("//") && !ReturnUrl.StartsWith("/\\"))
                    {
                        return Redirect(ReturnUrl);
                    }
                    return RedirectToAction("Index", "Home");
                }
                ModelState.AddModelError("", "The user name or password provided is incorrect.");
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
    }


  public class AccountMembershipService : IMembershipService
    {
        private readonly MembershipProvider _provider;

        public AccountMembershipService()
            : this(null)
        {
        }

        public AccountMembershipService(MembershipProvider provider)
        {
            _provider = provider ?? Membership.Provider;
        }


        public virtual bool ValidateUser(string userName, string password)
        {
            if (String.IsNullOrEmpty(userName)) throw new ArgumentException("Value cannot be null or empty.", "userName");
            if (String.IsNullOrEmpty(password)) throw new ArgumentException("Value cannot be null or empty.", "password");

            return _provider.ValidateUser(userName, password);
        }

    }

Membership in web.config of main application

<membership defaultProvider="CustomMembershipProvider">
  <providers>
    <clear />
    <add name="CustomMembershipProvider" type="QUBBasketballMVC.Infrastructure.CustomMembershipProvider" connectionStringName="UsersContext" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
  </providers>
</membership>

 public class CustomMembershipProvider : MembershipProvider
{
     public override bool ValidateUser(string username, string password)
    {

        using (var usersContext = new UsersContext())
        {
            var requiredUser = usersContext.GetUser(username, password);
            var userApproved = usersContext.GetUserMem(username);
            if (userApproved == null) return false;
            return (requiredUser != null && userApproved.IsApproved != false);
        }
    }
}

What happens when I run ShouldNotAcceptInvalidUser() with Option1 uncommented I can see that MembershipService is a Mock<IMembershipService> in the AccountController but it never steps into MembershipService.ValidateUser on the login Action.

When I run with option2 uncommented the same thing happens except MembershipService is Mock<AccountMembershipService> in the accountcontroller and it hits the AccountMembership Contstructor with null parameters, which in turn sets is to SqlMembershipProvider as Membership.Provider is System.Web.Security.SqlMembershipProvider

Also ExampleForMockingAccountMembershipService() doesn't seem to hit the ValidateUsermethod at all in CustomMembershipProvider and always returns true.

Hopefully this is enough to see where i'm going wrong!! :/

Thanks for providing your code. I think I have a much better handle on what you're trying to do now.

For your ShouldNotAcceptInvalidUser test, you should definitely mock IMembershipService instead of AccountMembershipService (choose option 1 over option 2). Since your controller is your SUT, it should be the only "real" class in the test, in order to minimize the number of moving parts.

With option 1, there's no reason to expect that MembershipService.ValidateUser would step into any code. The MembershipService is a mock object - and you've explicitly told it to just always return false when that method is called. Based on the code here, and using option 1, I'd expect this test to pass.

In your other test, ExampleForMockingAccountMembershipService, you're mocking your SUT which is something you should not do. Your SUT should be the only "real" object in your test. That means all collaborating objects should be mocked, leaving the SUT to be the only object doing anything meaningful. (That way, if the test fails, you know for sure that it's because of a bug in the SUT.)

(Note: ValidateUser was always returning true here because you mocked the SUT, and explicitly told it to always return true. This is why it's never a good idea to mock your SUT - mocking changes the behavior that you're trying to test.)

Based on the code you provided, I'm guessing that the reason you mocked CustomMembershipProvider is because it doesn't fully implement its abstract base class MembershipService. If this is indeed the case, then you will need to implement the missing methods manually, instead of relying on the mocking framework to provide default implementations.

Here is what I believe you were intending this test to look like:

    [Test]
    public void ExampleForMockingAccountMembershipService()
    {
        var validUserName = "connorgerv";
        var validPassword = "passwordd1";
        var sut = new CustomMembershipProvider();

        Assert.IsTrue(sut.ValidateUser(validUserName, validPassword));
    }

Something to look out for here is the fact that CustomMembershipProvider instantiates one of its dependencies: UsersContext. In a unit test, since CustomMembershipProvider is your SUT, you'd want to mock all of its dependencies. In this situation, you could use dependency injection to pass an object responsible for creating this dependency (e.g., an IUsersContextFactory), and use a mock factory and context in your test.

If you don't want to go that route, then just be aware that your test could fail because of a bug in CustomMembershipProvider or a bug in UsersContext.

So, the general logic in your tests is sound; the problems mainly stem from confusion on the role of mock objects in your tests. It's kind of a tough concept to get at first, but here are some resources that helped me when I was learning this:

"Dependency Injection in .Net" by Mark Seemann

"Test Doubles" by Martin Fowler

I've read some articles (Stackoverflow, Wikipedia, Simone Busoli, etc.) about Inversion of Control (IoC) and am starting to get my head around the concept. I've also been studying the Entity Framework (EF) and am wondering where specifically IoC is present within the EF? Here's a simple EF example I've been looking at: (EF Code First: new DB)

Inversion of Control is a pattern that aims at loosely coupling an application. It puts the application in charge of all of its dependencies (whether or not they are in libraries or frameworks).

EF is not an application, it is a library. You can wire it up with IoC, but since it is not an application, it contains no IoC.

That said, it is possible to develop frameworks and libraries to be IoC or DI (dependency injection) friendly. There are a couple of great articles on that topic:

Mark Seemann (the author of that blog) has written a great book on the subject of DI in .NET, which I highly recommend because there is a lot of misinformation and outdated information on the web about IoC and DI. I am confident once you read the book you will understand how to use IoC with EF, but it is not something that can be answered in a paragraph or two.