Skip to content

Dependency Resolver

Arif Yayalar (@ayayalar) edited this page Aug 24, 2018 · 1 revision

DependencyResolver is a typical service locator pattern that can be implemented to obtain service instances.

Implement IDependencyResolver

class DependencyResolver : IDependencyResolver
{
    private Dictionary<Type, object> _dict = new Dictionary<Type, object>()
    {
        { typeof(IOrderRepository), new OrderRepository() }
    };

    public object GetService(Type serviceType) => _dict[serviceType];
	
    public IEnumerable<object> GetServices(Type serviceType) => 
        Enumerable.Empty<object>();	
}

Pass it to RuleEngine

var re = RuleEngine<Foo>.GetInstance(new Order(), new DependencyResolver())
.ApplyRules(new UpdateTrackingNumber())
.Execute()

Access it in the rules

class UpdateTrackingNumber : Rule<Order>
{
    IOrderRepository orderRepository;

    public override void BeforeInvoke()
    {	
        orderRepository = (IOrderRepository)
            DependencyResolver.GetService(typeof(IOrderRepository));	
    }

    public override IRuleResult Invoke()
    {
        Model.TrackingNumber = orderRepository.GetTrackingNumber();
        
        return null;
    }
}