kayak
kayak

Reputation: 1845

Resolving dependency in Unity

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)
    {  }
}

Upvotes: 2

Views: 155

Answers (3)

kayak
kayak

Reputation: 1845

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

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

Upvotes: 0

Wiktor Zychla
Wiktor Zychla

Reputation: 48230

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.

Upvotes: 1

Steven
Steven

Reputation: 172606

Just do this:

container.RegisterType<IUserRepository, UserEntityRepository>();

Upvotes: 0

Related Questions