Advanced Usage

Sample interfaces/classes used can be found at the bottom of this page.

All samples assumes that you have included the namespace for the static Crosser.Resolver container.

// include the namespace
using Crosser.Resolve;

Dependency Injection

If you take a look at the sample classes you can see a common way to decouple concrete implementation from each other. Basically all we do is using the interfaces instad of the concrete type so that we can change the implementation with minimal efforts.

Register

Register the ICarService to CarService, also pass ICarRepository to the ctor since it needs one

One<ICarService>.As(()=>new CarService(One<ICarRepository>.Get()));

Register the ICarRepository to CarRepository so that the mapping above will be ok

One<ICarRepository>.As(()=> new CarRepository());

Resolve

Now when we ask for the ICarService we will get a CarService with the ICarRepository registered

var carService = One<ICarService>.Get();
foreach(var car in carService.GetFastestCars(3))
{
    Console.WriteLine("Name: {0}, Speed: {1}",car.Name, car.TopSpeed);
}

Property Injection

Above we used Dependency Injection by passing interfaces on the constructor, but we could also do Property Injection if the interface we map has public properties.

Interfaces

public interface ISomeInterface
{
    IAnotherInterface SomeProperty {get;set;}
}
public interface IAnotherInterface
{

}

Register

One<ISomeInterface>.As(()=>new SomeInterfaceImplementation{SomeProperty = One<IAnotherInterface>.Get();});
One<IAnotherInterface>.As(()=> new AnotherInterfaceImplementation());

Resolve

// TODO: To test this... Implement ISomeInterface in SomeInterfaceImplementation and IAnotherInterface in SomeProperty

Sample Code

interfaces and classes used in this page

Model

public class Car
{
    public int Id{get;set;}
    public string Name{get;set;}
    public int TopSpeed{get;set;}
}

Interfaces

public interface ICarService
{        
    IEnumerable<Car> GetFastestCars(int maxHits);
} 

public interface ICarRepository
{
    IEnumerable<Car> GetFastestCars(int maxHits);
} 

implementations

public class CarRepository : ICarRepository
{
    public IEnumerable<Car> GetFastestCars(int maxHits = 3)
    {
        return new List<Car>(){
            new Car{Id = 1, Name="Ferrari 1", TopSpeed=365},
            new Car{Id = 2, Name="Ferrari 2", TopSpeed=400},
            new Car{Id = 3, Name="Ferrari 3", TopSpeed=332},
            new Car{Id = 4, Name="Ferrari 4", TopSpeed=450},
            new Car{Id = 5, Name="Ferrari 5", TopSpeed=320},
        }.OrderByDescending(p => p.TopSpeed).Take(maxHits);
    }
}

public class CarService : ICarService
{
    protected ICarRepository Repository;
    public CarService(ICarRepository repository)
    {
        Repository = repository;
    }
    public IEnumerable<Car> GetFastestCars(int maxHits = 3)
    {
        return this.Repository.GetFastestCars(maxHits);
    }
}