views:

39

answers:

1

I'm having a difficult time registering my types for Unity 2 in my unit tests.

Here's a snippet of the class under test:

public class SomeService : ISomeService
{
    private int SomeVar { get; set; }

    [Dependency]
    public ISessionManager SessionManager { get; set; }

    public SomeService()
    {
        SomeVar = SessionManager.Get<int>("SomeVar");
    }
}

Here's what I have in my MSTest ClassInitialize method:

private static ISomeService _someService;
private static IUnityContainer _unityContainer;
[ClassInitialize]
public static void MyClassInitialize(TestContext testContext)
{
    var mockSessionManager = new Mock<ISessionManager>();

    mockSessionManager.Setup(foo => foo.Get<int>(It.IsAny<string>())).Returns(1);

    _unityContainer = new UnityContainer()
        .RegisterInstance(mockSessionManager.Object)
        .RegisterType<ISomeService, SomeService>(
            new InjectionProperty("SessionManager"));

    _someService = _unityContainer.Resolve<IAdditionalCoveragesService>();
}

For every test method that I have, when I debug and step into the constructor of SomeService, it says that SessionManager is null. What am I doing in wrong in trying to register my types in Unity?

Note - I am using Moq to set up a mock session manager that should be injected into SomeService.

Thanks!!!

+1  A: 

Because it's an injection property: the property is set after being created. To use SessionManager in the constructor you should use constructor injection:

public class SomeService : ISomeService
{
    private int SomeVar { get; set; }

    public ISessionManager SessionManager { get; private set; }

    public SomeService(ISessionManager sessionManager)
    {
        SessionManager = sessionManager;
        SomeVar = SessionManager.Get<int>("SomeVar");
    }
}

and:

_unityContainer = new UnityContainer()
        .RegisterInstance(mockSessionManager.Object)
        .RegisterType<ISomeService, SomeService>();
onof
Right, but i'd rather not have to create a new constructor to set the SessionManager. Is it not possible to inject the property before the constructor?
Chris Conway
How can set a property before an object exists? If you don't want to add a constructor, you can put your logic in the setter of SessionManager
onof
Yes, your SessionManager will always be null in the constructor, period, DI container or not. Properties just don't work that way.
Chris Tavares