-
Notifications
You must be signed in to change notification settings - Fork 7
Dependency Injection
Arif Yayalar (@ayayalar) edited this page Apr 6, 2019
·
2 revisions
This example uses Autofac however any DI component can be used using the approach demonstrated below.
Install Autofac
Install-Package Autofac
Implement IDependencyResolver (uses autofac)
class DependencyResolver : IDependencyResolver
{
IContainer _container;
public DependencyResolver()
{
var _builder = new ContainerBuilder();
_builder.RegisterType<MyService>().As<IService>();
_container = builder.Build();
}
public object GetService(Type serviceType)
{
using (var scope = _container.BeginLifetimeScope())
{
return scope.ResolveOptional(serviceType);
}
}
public IEnumerable<object> GetServices(Type serviceType)
{
using (var scope = _container.BeginLifetimeScope())
{
var enumerableServiceType = typeof(IEnumerable<>).MakeGenericType(serviceType);
var instance = scope.Resolve(serviceType);
return (IEnumerable<object>)instance;
}
}
}
Create Rule
class UpdateTrackingNumber : Rule<Order>
{
IService _service
// Dependency Resolver resolves IService instance
public ValidatePhoneNumberIs10Digits(IService service)
{
_service = service
}
public override IRuleResult Invoke()
{
_service.UpdateTrackingNumber();
return null;
}
}
Pass it to RuleEngine
Notice only the type
of the rule is added to the rule engine rather than its instance
// Dependency Resolver resolves UpdateTrackingNumber instance
var ruleEngine = RuleEngine<Order>.GetInstance(new Order(), new DependencyResolver());
ruleEngine.AddRule<UpdateTrackingNumber>();
ruleEngine.Execute()
Synchronous Rules |
Asynchronous Rules |
Parallel Rules |
Reactive Rules |
Proactive Rules |
ExceptionHandler Rules |