0

I am going through the following tutorial. I'm at the part

IUnityContainer BuildUnityContainer()
{
    var container = new UnityContainer();

    container.RegisterType<IStoreService, StoreService>();
    container.RegisterType<IController, StoreController>("Store");        

    return container;
}

The question I have is how do I do multiple controllers? For instance if I have Store, Music, and Owner controllers, each with their own I[Name]Service

1
  • With Unity, you don't have to register those controllers at all. Unity can resolve concrete types. But it's wise to still verify whether those controllers can be resolved correctly (inside a unit test for instance). Commented Jun 7, 2013 at 16:30

4 Answers 4

2

The new Unity 3 provides an integration point for MVC 4 out of the box. All the details on how to use it are here: http://msdn.microsoft.com/en-us/library/dn178463(v=pandp.30).aspx#sec17

You can also combine this with the registration by convention feature to register all your mappings like IFoo -> Foo: http://msdn.microsoft.com/en-us/library/dn178463(v=pandp.30).aspx#sec23

Regarding controllers, you do not need to register them explicitly in Unity, because if you ask Unity to resolve an instance of a concrete type that was not previously registered, it will build one up (injecting the dependencies using the longest constructor). MVC will ask Unity using the concrete types of the controllers, so they will work automatically.

Sign up to request clarification or add additional context in comments.

Comments

1

you have to register each of those in the same way. Or you might have to write a logic where you can get all possible types using reflaction and register those within loop.

Comments

0

Take a look at http://autoregistration.codeplex.com/. It does autoregistration of types for unity. Most other IOC containers does this as well.

Comments

0

Take a look at http://weblogs.asp.net/shijuvarghese/archive/2008/10/24/asp-net-mvc-tip-dependency-injection-with-unity-application-block.aspx.

Step 3 contains code for injecting dependencies to controller Also include the following code from Step 4:

ControllerBuilder.Current.SetControllerFactory(new myFinance.Web.Controllers.UnityControllerFactory(container));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.