开发者

How would dependency injection apply to this scenario?

开发者 https://www.devze.com 2023-03-18 21:56 出处:网络
I\'m using Ninject for constructor injection to create my concrete objects on the fly.However, I have a scenario where the class contains a method that accepts a string.Based on the value of the strin

I'm using Ninject for constructor injection to create my concrete objects on the fly. However, I have a scenario where the class contains a method that accepts a string. Based on the value of the string, I would like to obtain a specific class. I accomplished this by creating a factory class to return the concrete class but wasn't sure if this was the best way. Any suggestions?

//Service class
public int GetEmployeeVacationDays(string employeeType)
{
  IEmployee employee = EmployeeFactory.CreateEmployee(employeeType);
  return employee.VacationDays();
}

//Factory class
public static IEmployee CreateEmployee(str开发者_如何学Going employeeType)
{
   if(employeeType == "Salary")
   {
      return new SalariedEmployee();
   }
   else
   {
      return new HourlyEmployee();
   }
}


Dependency injection doesn't apply to your scenario. That's the factory pattern. You could configure Ninject to use the factory pattern to provide dependencies if you will for certain objects.

In fact you could entire replace the factory pattern with named bindings:

Bind<IEmployee>().To<FooEmployee>().Named("foo");
Bind<IEmployee>().To<BarEmployee>().Named("bar");
Bind<IEmployee>().To<BazEmployee>().Named("baz");


assuming that employeeType is a valid class name:

return System.Activator.CreateInstance(Type.GetType(className))
0

精彩评论

暂无评论...
验证码 换一张
取 消