Pergunta

I've looked through a number of threads here (perhaps I'm using the wrong terminology), but I'm converting a Web Application over to use IoC via NInject. My other IoC projects were fairly small so it wasn't a big issue, but what is the recommended practice for the following situation...

My object's structure looks like this...

public class Address
{
    public virtual string Street { get; set; }
    public virtual City City { get; set; }
}

City being it's own object...

public class City
{
    public virtual string Name { get; set; }
}

Now I have been handling the inevitable "Object is null" exception as follows...

public void DoThing()
{
    new Address address();
    address.Street = _street;
    address.City = new City();
    address.City.Name = _cityName;
    DoOtherThing(address);
}

This was fine for the smaller projects... but now that we're talking something bigger it becomes a real chore. (Add another object to my object, it could mean I need to do this in over 100 places, assuming I find them all)

Prior to IoC this was handled easily by doing stuff like this...

public class Address
{
    private string street;
    private City city;

    public Address()
    {
        street = string.Empty;
        City = new City();
    }

    public string Street 
    { 
        get { return street; } 
        set { street = value; }
    }
}

What I'm trying to figure out (and perhaps I'm just completely missing this detail in the guides I've read) is how can I do the equivalent in IoC in an elegant manner?

The structure I'm following is based off the one presented by Tony Sneed at http://www.develop.com/onionarchitecture

The only notable difference is I don't have anything at my services level yet because most of our stuff is simply reading from/writing to the database with very little notable manipulation in between. (I will likely have things I'll need to put in on the service level, but just not hit any yet, still not entirely clear exactly what belongs at that level verses the repository.)

Let me know if there is anymore details I can provide to be helpful (The IoC is working fine, I just need to tackle the above mentioned issue to keep maintainability reasonable)

Foi útil?

Solução

If all you're doing is creating an empty object, then there is no real reason to use IoC (A better term is Dependency Injection, because it's more specific). Unless you're going to pass a loaded City object to your Address object, just keep using new in your constructor. There is no benefit to using IoC/DI in this situation.

You should use DI when you need to pass a dependency to an object at runtime. While this is technically a dependency, the fact that it's a simple empty object doesn't make it a good candidate.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top