I'm having problem in passing parameter dynamically to class constructor using simple injector.
I have following code structure.
Controller example:
public class HomeController : Controller
{
private readonly ICheckService _checkService;
public HomeController(ICheckService checkService)
{
_checkService= checkService;
}
// GET: Home
public ActionResult Index()
{
var list = _checkService.GetAll();
return View(list);
}
}
Service layer (in this layer I need to pass the two constructor parameter for CheckRepository<T> which is implementing ICheckRepository<T>. How do I achieve this using simple injector? I tried but not getting solution around. One example in order to achieve would be really grateful)
public interface ICheckService
{
List<CheckType> GetAll();
}
public class CheckService : ICheckService
{
private readonly ICheckRepository<CheckType> _checkRepository;
public CheckService(ICheckRepository<CheckType> checkRepository)
{
_checkRepository= checkRepository;
}
public List<T> GetAll()
{
return _checkRepository.GetAll().ToList();
}
}
Repository Layer:
public abstract class RepositoryBase<T> where T : class
{
public string Types { get; set; }
public string Segment { get; set; }
public RepositoryBase(string type)
{
Types = type;
}
public RepositoryBase(string type, string segment)
{
Types = type;
Segment = segment;
}
}
public interface ICheckRepository<T> where T : class
{
IEnumerable<T> GetAll();
}
public class CheckRepository<T> : RepositoryBase<T>, ICheckRepository<T> where T : class
{
public CheckRepository(string types, string segment)
: base(types, segment)
{
}
public IEnumerable<T> GetAll()
{
var list = new List<T>();
using (DbAccess dbAccess = new DbAccess(ConnectionString, DatabaseType.SqlServer))
{
return dbAccess.ExecuteReader<T>(StoredProc, CommandType.StoredProcedure).ToList();
}
}
}
My Simple Injector initializer class:
public static void InitializeInjector()
{
var container = new Container();
InitializeContainer(container);
container.RegisterMvcControllers(Assembly.GetExecutingAssembly());
container.RegisterMvcIntegratedFilterProvider();
container.Verify();
DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
}
private static void InitializeContainer(Container container)
{
container.Register(typeof(IFilterRepository<>), typeof(FilterRepository<>));
//Here is where I am struggling to bind dynamic constructor parameter registering
}
Does anyone have any solution for the above code?
Thanks again.
new CheckService(new FilterRepository<CheckType>(whatgoedhere?)). Please show examples of the different repositories that you want to have created. This gives us the knowledge of what you are trying to achieve and it allows us to formulate the correct answer to your question. - Steven