I am writing a small utility for myself so whilst I am using Unity currently, I can change to a different IoC container if it will allow me to get around this problem.
I want to create a class that is given some data when it is created, but is immutable after that, normally I would do this with:
class SomeItem
{
public SomeItem(string name)
{
Name = name;
Hash = new SomeHashingClass().GenerateHash(name);
}
public string Name { get; private set; }
public string Hash { get; private set; }
}
The problem is the dependency on SomeHashingClass in the constructor, how do I inject it whilst keeping the object immutable?
One way would be to have the constructor take just the dependency, then have a method which is the same as the current constructor to do the real work. However I hate that idea as it could leave the object in a state of existing but being totally invalid. And code would need to be written to make sure the method can only be called once.
The other way I can see to do it is to create a 'SomeItemFactory' class that unity resolves, then manually doing the dependency injection for SomeItem, however this doubles the amount of code:
class SomeItemFactory
{
IHashingClass _hashingClass;
public SomeItemFactory(IHashingClass hashingClass)
{
_hashingClass = hashingClass;
}
public SomeItem Create(string name)
{
return new SomeItem(_hashingClass, name);
}
}
class SomeItem
{
public SomeItem(IHashingClass hashingClass, string name)
{
Name = name;
Hash = hashingClass.GenerateHash(name);
}
public string Name { get; private set; }
public string Hash { get; private set; }
}
Please tell me there is a clean way to do this. Why is there no method like:
unityContainer.Resolve<SomeItem>("the items name");