I'm new to dependency injection but fast becoming a big fan. However I can't seem to find anything that satisfactorily describes how to deal with objects at run time which are not injected from a container. I'll refer to same as data objects.
Consider the following, (forgive me if the following shows I've completely missed the point of DI):- In the old days I would code an object as follows: -
public class Person
{
public string Name { get; set; }
public string EmailAddress { get; set; }
public void DoSomething(params string[] paremeters)
{
//code to do something with this person using parameters
}
public void DoSomethingElse()
{
//code to do something else with this person
}
}
Now with DI I might do the following: -
public class Person
{
public string Name { get; set; }
public string EmailAddress { get; set; }
}
public interface IPersonService
{
void DoSomething(Person person, params string[] paremeters);
void DoSomethingElse(Person person);
}
public class PersonService : IPersonService
{
public void DoSomething(Person person, params string[] paremeters)
{
//code to do something with this person using parameters
}
public void DoSomethingElse(Person person)
{
//code to do something else with this person
}
}
And the IPersonService service would be 'injected' through constructors into any processes that needed it. The problem is that it feels wrong having to add a Person parameter to every procedure and method in the PersonService but no alternatives seem to work any better.
For example I could use something like
Person _person;
void Configure(Person person)
{
_person = person
}
..in all my injected services which needed transient data, but then you run into state problems and all such services need to be transient. Again not happy with that.
In this example the person might come from a database, a screen form, a file, have been selected from a list in a directory or anywhere else.
I am aware that I could inject my data using a data repository (class to access the data and all the CRUD stuff) and indeed I have every intention of doing that but that still doesn't solve the problem of how I tell the service, in this case, which person to access unless of course I add a procedure into the service which includes a parameter for the identity of the person and then use the repository to go and fetch the person... but that then works just like the Initialise approach which results in State problems. It also relies on remembering to call the procedure in the service to configure the data.
My question is, what's the best practise here? Please keep it simple.
Many thanks