I am looking for suggestions on the best way to design objects for IoC
Suppose I have an object (Service) that has a dependency on a DataContext that is registered in Ioc.
But this also requires the name property, I could create an object like this:
class Service { public Service(IDataContext dataContext, string name) { this._dataContext = dataContext; this._name = name } public string Name { get { return _name; } } }
The problem is that with Ioc containers it is very difficult to use as a string object, such as a name, it is not easy to register and use is complicated with the Ioc container: Therefore, the resolution becomes confusing:
var service = Ioc.Resolve<Service>( ?? )
Another approach is to develop it as follows:
class Service { public Service(IDataContext dataContext) { this._dataContext = dataContext; } public string Name { get; set; } }
Now the resolution is simpler:
var service = Ioc.Resolve<Service>(); service.Name = "Some name";
A single downsite indicates that the name is no longer required. I would like to hear from DI or IoC experts how they will design this and still remain agnostic enough for a specific Ioc container technology.
I know that a lot depends on how you want to use this, option 2 would be ideal if the name were really optional. But in the case where a name is required, you can add a verification step at another point in the code, but rather go to a project to make Ioc easier.
Thoughts?
c # dependency-injection inversion-of-control constructor-injection
Andre
source share