3

I am using Unity with MVC and NHibernate. Unfortunately, our UnitOfWork resides in a different .dll and it doesn't have a default empty .ctor. This is what I do to register NHibernate:

var connectionString = ConfigurationManager.ConnectionStrings
    ["jobManagerConnection"].ConnectionString;
var assemblyMap = ConfigurationManager.AppSettings["assemblyMap"];
container.RegisterType<IUnitOfWork, UnitOfWork>(
    new ContainerControlledLifetimeManager());

In my WebController I have this:

/// <summary>Gets or sets UnitOfWork.</summary>
[Dependency]
public IUnitOfWork UnitOfWork { get; set; }

The problem is that the constructor of UnitOfWork expects 2 mandatory strings. How I can setup the RegisterType for this Interface in order to pass the two parameters retreived from the web.config? Is it possible?

2 Answers 2

4

Something like this should do it:

var connectionString = ConfigurationManager.ConnectionStrings
    ["jobManagerConnection"].ConnectionString;
var assemblyMap = ConfigurationManager.AppSettings["assemblyMap"];

container.RegisterType<IUnitOfWork, UnitOfWork>(
    new InjectionConstructor(connectionString, assemblyMap),
    new ContainerControlledLifetimeManager());
Sign up to request clarification or add additional context in comments.

2 Comments

Yep, Mark you are right. I just posted a different way. Sorry but the docs in Unity still lack.
Mark's got it almost right - you need to put the lifetime manager first: container.RegisterInstance<IUnitOfWork, UnitOfWork>( new ContainerControlledLifetimeManager(), new InjectionConstructor(connectionString, assembyMap));
1

Easier than I though:

        var connectionString = ConfigurationManager.ConnectionStrings["jobManagerConnection"].ConnectionString;
        var assemblyMap = ConfigurationManager.AppSettings["assemblyMap"];
        container
            .RegisterType<IUnitOfWork, UnitOfWork>(new ContainerControlledLifetimeManager())
            .Configure<InjectedMembers>()
            .ConfigureInjectionFor<UnitOfWork>(new InjectionConstructor(connectionString, assemblyMap));

1 Comment

I couldn't get Mark's syntax for the constructor parameters to work for some reason, but your lengthier implementation worked. Thanks!

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.