2

I copied a repository pattern sample which uses AutoFac as IOC, But in my project i use UNITY, Any idea on how to write this in Unity 3.0

AutoFac:

  builder.Register<IUserRepository>(x => new UserEntityRepository (x.Resolve<IDataContextFactory<SampleDataContext>>())).SingleInstance();

Class where IOC will be injected:

public class UserEntityRepository : EntityRepository<User, SampleDataContext>, IUserRepository
{
    public UserEntityRepository(IDataContextFactory<SampleDataContext> databaseFactory)
        : base(databaseFactory)
    {  }
}
2
  • Are you open for configuration based solution or just code based? Commented Dec 27, 2013 at 17:18
  • I'm looking for code based Commented Dec 27, 2013 at 17:31

3 Answers 3

1

Unity would resolve the constructor parameter automatically, if the dependency is registered. The simplest version would be then

container.RegisterType<IUserRepository, UserEntityRepository>( 
   new ContainerControlledLifetimeManager() );

However, what you do is slightly more complicated as it gives you more freedom in selecting specific parameter values. In Unity you can have this with the injection factory:

container.RegisterType<IUserRepository>( 
    new InjectionFactory(
       c => new UserEntityRepository( 
         c.Resolve<IDataContextFactory<SampleDataContext>> ), 
    new ContainerControlledLifetimeManager() );

This pretty much seems like your autofac version. Remember to register the data context factory first.

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

1 Comment

Thanks Wiktor, the injectionFactory helped. I have tweaked the code a bit in my answer below..
0

Just do this:

container.RegisterType<IUserRepository, UserEntityRepository>();

Comments

0

This one worked as i expected.., (based on Wiktor's solution)

        container.RegisterType<IUserRepository>                
           (new ContainerControlledLifetimeManager(),
           new InjectionFactory(c => new UserEntityRepository 
              (new DefaultDataContextFactory<SampleDataContext>())));

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.