I am using Simple Injector for test purpose but prety new on OOP. I am trying to create loosly couple classes. Here is the my scenario.
I have User repo and interface like this.
public class UserRepository:IUserRepository
{
public void Add(Model.User user)
{
Console.WriteLine("Name:"+user.Name+"\n"+"SurName:"+user.SureName);
}
public void Delete(int id)
{
throw new NotImplementedException();
}
}
public interface IUserRepository
{
void Add(User user);
void Delete(int id);
}
My TestInjectedClass
Class and interface something like this which I am planng to use in Programe Main.
public class TestInjectedClass:ITestInjectedClass
{
private readonly IUserRepository _userRepository;
public TestInjectedClass(IUserRepository userRepository)
{
_userRepository = userRepository;
}
public void UserRepoRun()
{
var user = new User() {Id = 1,Name = "ada",SureName = "stack"};
_userRepository.Add(user);
}
}
public interface ITestInjectedClass
{
void UserRepoRun();
}
And My console programme looks like this:
class Program
{
static ITestInjectedClass _testInjectedClass;
private static IUserRepository _userRepository;
static void Main(string[] args)
{
_testInjectedClass= new TestInjectedClass(_userRepository);
_testInjectedClass.UserRepoRun();
Console.ReadLine();
}
public Program()
{
Bootstrap.Start();
}
}
BootStrap class here:
class Bootstrap
{
public static void Start()
{
var container = new Container();
// Register your types, for instance:
container.Register<IUserRepository, UserRepository>(Lifestyle.Singleton);
container.Register<ITestInjectedClass, TestInjectedClass>(Lifestyle.Singleton);
//container.Register<IUserRepository, TestInjectedClass>(Lifestyle.Singleton);
//container.Register<IUserContext, WinFormsUserContext>();
container.Register<TestInjectedClass>();
// Optionally verify the container.
container.Verify();
}
}
My problem when I run programme,I am getting value exception on the _userRepository
inside TestInjectionClass
.
How can properly injected TestInjectionClass
and UserRepository
to Main Programe. Thanks
The problem is because you are calling your
Bootstrap
code inProgram
class instance constructor.So, actually when you start your program the execution environment, is calling entry point method
Main
. And your instance constructor is never executed.Try changing your entry point method
Main
and 'Bootstrap' class code:Please use SimpleInjector
Sample please refer
http://www.c-sharpcorner.com/UploadFile/4d9083/dependency-injection-using-simple-injector/
You need to make
Bootstrap.container
available inProgram.Main
and then use it to create instances of classes instead of directly calling their constructors directly:Of course you will need to expose it in
Bootstrap
for that to work:And call
Bootstrap.Start
fromProgram.Main
: