C# – SubSonic SimpleRepository and Dependency Injection

cdependency-injectionsubsonic

On a bit of a learning curve. Know one of you gurus can help me out.

I'm looking into SubSonic (SimpleRepository) and StructureMap. Really trying to get my head around them both.

I want to use SimpleRepository for the ease of use and letting my models define the database rather than pull off of or create a DB structure initially.

I create a concrete class that inherits from SimpleRepository

public class DataRepository : SimpleRepository
{
    public DataRepository() :   
        base("Application", SimpleRepositoryOptions.RunMigrations) 
        { }  
}

Add this to my Application Initialization

ObjectFactory.Initialize(
    x => x.ForRequestedType<DataRepository>()  
        .TheDefaultIsConcreteType<DataRepository>()  
        .CacheBy(InstanceScope.Hybrid));

And now I'm sure that everywhere in the app i use the same SimpleRepository.

Am I making this too complex? Or am I on the right track here. I know that you don't know all the other particulars so speak to me in generalities too. Thanks.

Best Answer

I think you missed one of the core ideas of DI here. That idea being the use of interfaces to abstract the calling code from the concrete class that actually implements the functionality.

public interface IDataRepository { }

internal class DataRepository : SimpleRepository, IDataRepository
{
}

ObjectFactory.Initialize(
    x => x.ForRequestedType<IDataRepository>()  
        .TheDefaultIsConcreteType<DataRepository>()  
        .CacheBy(InstanceScope.Hybrid));

Now all the client code should resolve/reference only the IDataRepository interface.