MVC, Unity and Dependency in another project

Topics: General discussion
Aug 11, 2012 at 11:16 PM
Edited Aug 11, 2012 at 11:39 PM

Hi,

I have an app build with MVC4 which uses my class library. Both use Unity as a container. DI works in MVC and it works in my test for the library. But when I use object from class library in MVC controller the ocject's properties are not resolved. Here's an example:

Class Library:

public class SomeClass : ISomeClass {
  [Dependency]
  public ISomeService theservice { get;set; }
  ...
}
MVC app:
public ActionResult UseTheService(...)
{
  ISomeClass sco = SomeFactory.Create();
  // ** without this line sco.theservice IS NULL **
  container.BuildUp((CloudGalleryAzure.Gallery)newGallery);
}
The last line ruins the whole idea.
Any idea why Dependency attribute doesn't work in the Class Library? How does it work?
I appreciate it.
Aug 12, 2012 at 12:19 AM

It's hard to tell exactly what is going on but one thing I notice is that the dependency is an interface of type ISomeService.  Unity needs to be told what concrete type to inject when it sees the ISomeService interface.  

Usually you would configure the container to map the interface to a concrete type:

container.RegisterType<ISomeService, ConcreteSomeService>();

If you need to use factories then you could either inject the factory itself or use one of the strategies discussed in this thread on the Unity discussion forum.  Also of interest may be Annotating Objects for Property (Setter) Injection.

--
Randy Levy
Enterprise Library support engineer
entlib.support@live.com