We are trying to implement repository pattern in using Linq2SQl and the data context is initialized lazily.
Repository class implements IRepository
public class Repository<T> : IRepository<T> where T : class
{
private readonly Table<T> _table;
public Repository(IDataContextAdapter dataContextAdapter)
{
_table = dataContextAdapter.Context.GetTable<T>();
}
...
}
Data Access uses delegates to Repository
public class UserDataAccess : IUserDataAccess
{
private readonly IRepository<User> _userRepository;
public UserDataAccess(IDataContextAdapter dataContextAdapter,
Func<IDataContextAdapter, IRepository<User>> userRepository)
{
_userRepository = userRepository(dataContextAdapter);
}
}
I like to know how to define the repositories generically in unity container.
Currently I have the following, but I don't want to repeat it for every concrete repository class like User, Employer etc.
UnityContainer.RegisterType<Func<IDataContextAdapter, IRepository<User>>>(
new InjectionFactory(c =>
new Func<IDataContextAdapter, IRepository<User>>(
context => new Repository<User>(context))
)
);
I am looking for a way to define the types generically, something like
UnityContainer.RegisterType<Func<IDataContextAdapter, IRepository<T>>>(
new InjectionFactory(c =>
new Func<IDataContextAdapter, IRepository<T>>(
context => new Repository<T>(context))
)
);
I have tried applying typeof operation with on '<>', but didn't had much success.
The main reason for using delegates in DataAccess is to instantiate them when needed instead of creating them at the beginning of the unity container. For eg. your app has multiple tabs and user can work submit work at the same time. If you initiate the DataContext at the beginning of the app, it would be shared by all tabs. – skjagini Mar 17 '11 at 14:24