问题
I have a class similar to the following:
public class CarAttributes
{
private readonly ICarRepository _carRepository;
private readonly int _carId;
public CarAttributes(ICarRepository carRepository, int carId)
{
_carRepository = carRepository;
_carId = carId;
}
public bool IsRegistered
{
get
{
return _carRepository.IsRegistered(_carId);
}
}
public bool IsStolen
{
get
{
return _carRepository.IsStolen(_carId);
}
}
}
I also have the following method (which is syntactically incorrect)
public CarAttributes GetCarAttributes(int carId)
{
return new CarAttributes(carId);
}
I am using Unity to inject the ICarRepository at runtime
container.RegisterType<ICarRepository, CarRepository>();
How do I inject CarAttributes with the CarRepository via Unity but allow the program to supply the carId?
Am I correct in thinking that i need a factory to do this?
Something perhaps like the following
public class CarAttributesFactory()
{
private readonly ICarRepository _carRepository;
public CarAttributesFactory(ICarRepository carRepository)
{
_carRepository = carRepository;
}
public CarAttributes GetCarAttributes(int carId)
{
return new CarAttributes(_carRepository, carId);
}
}
This allows unity to inject the factory with the dependency, but will also allow the program to specify the carId when the GetCarAttributes method is invoked.
However is this not going against the DI principles, as I am creating a dependency here between the CarAttributesFactory and the CarAttributes classes.
Is this the correct usage for using factories?
Also I have read about other DI frameworks having things such as TypedFactories for this kind of thing, although I would like to do it manually first to understand the concepts.
Here for example Unity - Constructor Injection with other parameter
Hope this makes sense.
EDIT: Example usage
From my MVC controller I need to be able to retrieve back a CarAttributes object for a specific carId which will be passed in via a view model. The CarAttributes class requires the use of one or more repositories (only one shown in this example), as well as a run time parameter passed in which is carId depending on what comes though the view model.
(I would also have to create an ICarAttributesFactory interface as well in order to inject the factory into the controller in the below example)
public SomeController : Controller
{
private readonly ICarAttributesFactory _carAttributesFactory;
public SomeController(ICarAttributesFactory carAttributesFactory)
{
_carAttributesFactory = carAttributesFactory;
}
public ActionResult Submit(DataViewModel model)
{
// model will contain a carId property
var carAttribs = _carAttributesFactory.GetCarAttributes(model.carId);
if(carAttribs.IsStolen)
{
// do something
}
}
}
来源:https://stackoverflow.com/questions/28073920/c-sharp-dependency-injection-passing-additional-parameter