tags:

views:

41

answers:

1

Hi All,

Im faced with an impending upgrade to an ASP.NET site and I am thinking of introducing DI using Unity. I have researched the ASP.NET DI side of things and have 2 options (Global.asax or IHttpModule). Im happy to use either.

As always, there is a legacy object model in place that I would like to upgrade/change. I would like to go down the route of Constructor injection (passing in the DAO) however, each object has a mix of static and instance methods that both currently call into the DB using SqlCommand objects themselves. I want this removed to provide DB independence, therefore can anyone suggest the best way to do the DI in this case? Im open to drastic changes if they are needed.

public class ExampleClass
{
       public ExampleClass(int test)
       {
           TestProperty = test;
       }

       public int TestProperty {get; set;}

       public int Save()
       {
          // Call DB and Save
          return 1;
       }

       public static ExampleClass Load(int id)
       {
          // Call DB and Get object from DB
          return new ExampleClass(1);
       }

}

Thanks for any suggestions

Matt

A: 

If you remove all static methods and introduce some abstractions you should be good to go:

public class ExampleClass
{
    public int TestProperty { get; set; }
}

public interface IRepository
{
    ExampleClass Load(int id);
    int Save();
}

public class RepositorySql: IRepository
{
    // implement the two methods using sql
}

and in your ASP page:

private IRepository _repo = FetchRepoFromContainer();
public void Page_Load() 
{
    var someObj = _repo.Load(1);
    // ... etc
}
Darin Dimitrov
My intention was to use Enterprise Library 4.1 for data access. The DAO im thinking of will largely be used to break up the Data access into functional areas. Also i didnt think Static methods could be defined in an interface? Im really looking for a way to use DI with static methods or for suggestions on a better way of doing things
Matt Belfast
Static methods cannot be defined in an interface.
Darin Dimitrov
i was thinking that removing the statics would be the way to go. I was just hoping to avoid it as it'll be a lot of work in limited time, as the whole site is being re-written too
Matt Belfast