Dynamic Constructor Injection using IWindsorInstaller - dependency-injection

I'm not sure if this is possible, but I though I'd ask the question anyway.
I have a scenario where I have a number of different tasks which send emails during processing.
The sending of emails is done via a custom class
public interface IEmailProvider
{
void SendEmail(some params);
}
public class EmailProvider : IEmailProvider
{
private readonly IEmailConfig _config;
public EmailProvider(IEmailConfig config)
{
_emailConfig = emailConfig;
}
public void SendEmail(some params)
{
// send the email using the params
}
}
I have some tasks which use the email provider, each providing their own implementation of IEmailConfig.
public class Task1 : ICommand
{
public Task1(IEmailProvider emailProvider)
{}
}
public class Task2 : ICommand
{
public Task2(IEmailProvider emailProvider)
{}
}
This is a basic example of my set up
public class TestInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
// Default email provider set up
container.Register(Component.For<IEmailProvider>().ImplementedBy<EmailProvider>()
.Named("DefaultEmailProvider")
.LifeStyle.Transient);
// Task 1 email config set up
container.Register(Component.For<IEmailConfig>().ImplementedBy<Task1EmailConfig>()
.Named("Task1EmailConfig"));
// Task 2 email config set up
container.Register(Component.For<IEmailConfig>().ImplementedBy<Task2EmailConfig>()
.Named("Task2EmailConfig"));
// Task 1 set up
container.Register(Component.For<ICommand>().ImplementedBy<Task1>()
.Named("Task1Command"));
// Task 2 set up
container.Register(Component.For<ICommand>().ImplementedBy<Task2>()
.Named("Task2Command"));
}
}
Is there a way I can make a decision, as each ICommand implementation is being resolved, as to which implementation of IEmailConfig to pass into the constructor of the EmailProvider class?
At the moment I register an EmailProvider instance for each task using the ServiceOverride functionality. This means that for each task that need to send emails, I have to almost duplicate the set up of the email provider and it's required config. I end up with something list this...
Component.For<IEmailConfig>()
.ImplementedBy<Task1EmailConfig>()
.Named("Task1EmailConfig"));
Component.For<IEmaiProvider>()
.ImplementedBy<EmailProvider>)
.Named("Task1EmailProvider")
.DependsOn(ServiceOverride.ForKey("config").Eq("Task1Config"));
Component.For<ICommand>()
.ImplementedBy<Task1>()
.DependsOn(ServiceOverride.ForKey("emailProvider").Eq("Task1EmailProvider")));
This will all be duplicated for each task.
The IEmailProvider implementation is always the same, it's only the IEmailConfig passed in that changes for each different task. I can't help thinking there must be a neater solution to the one I've got so far.

I think a couple of handler selectors would work for what you want. One for IEmailProvider and one for ICommand.
The IEmailProvider one could check the name of the IEmailProvider being activated (like "Task1EmailProvider") and strip off the "Provider" and add on "Config" -- which would give you the key "Task1EmailConfig" which could be used to resolve the particular IEmailConfig object.
Likewise, do the same thing for ICommand's. It would rely on you naming your IEmailConfig's consistently, but it would eliminate all of that hand-wiring you're doing now.

Related

How to access a DurableEntityClient in an injected class with Azure Durable Functions

I have an Azure Functions project that leverages Dependency Injection (Startup.cs injects services based on the different interfaces). Those services that implement the interfaces are using constructor dependency injection as well.
In one of those implementations, I want to call a method on a Durable Entity, but I prefer not to make the DurableEntityClient part of the method signature (as other implementations might not need the EntityClient at all). So therefore, I was hoping to see that IDurableEntityClient injected in the constructor of my class.
But it turns out the value is null. Wondering if this is something that is supported and feasible? (to have a DI-friendly way of injecting classes that want to get the EntityClient for the Functions runtime they are running in)
Some code snippets:
Startup.cs
builder.Services.AddSingleton<IReceiver, TableReceiver>();
Actual Function
public class ItemWatchHttpTrigger
{
private IReceiver _receiver;
public ItemWatchHttpTrigger(IReceiver receiver)
{
_receiver = receiver;
}
[FunctionName("item-watcher")]
public async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", Route = "item/{itemId}")]
HttpRequest request, string itemId, [DurableClient] IDurableEntityClient client, ILogger logger)
{
// Actual implementation
}
}
Referenced class
public class TableReceiver : IReceiver
{
private IDurableEntityClient _entityClient;
public TableReceiver(IDurableEntityClient client)
{
_entityClient = client; // client is null :(
}
}
Based on the answer of my github issue, it seems it is possible to inject this in Startup, since the 2.4.0 version of the Microsoft.Azure.WebJobs.Extensions.DurableTask package:
Some code snippets:
Startup.cs
builder.Services.AddSingleton<IReceiver, TableReceiver>();
builder.Services.AddDurableClientFactory();
Referenced class
public class TableReceiver : IReceiver
{
private IDurableEntityClient _entityClient;
public TableReceiver(IDurableClientFactory entityClientFactory, IConfiguration configuration)
{
_entityClient = entityClientFactory.CreateClient(new DurableClientOptions
{
TaskHub = configuration["TaskHubName"]
});
}
}
Github issue

How are domain events dispatched from within domain objects?

Domain objects shouldn't have any dependencies, hence no dependency injection either. However, when dispatching domain events from within domain objects, I'll likely want to use a centralised EventDispatcher. How could I get hold of one?
I do not want to return a list of events to the caller, as I'd like them to remain opaque and guarantee their dispatch. Those events should only be consumed by other domain objects and services that need to enforce an eventual consistent constraint.
See Udi Dahan's domain events
Basically, you register one or more handlers for your domain events, then raise an event like this:
public class Customer
{
public void DoSomething()
{
DomainEvents.Raise(new CustomerBecamePreferred() { Customer = this });
}
}
And all the registered handler will be executed:
public void DoSomethingShouldMakeCustomerPreferred()
{
var c = new Customer();
Customer preferred = null;
DomainEvents.Register<CustomerBecamePreferred>(p => preferred = p.Customer);
c.DoSomething();
Assert(preferred == c && c.IsPreferred);
}
This is basically implementing Hollywood Principle (Don't call us, we will call you), as you don't call the event handler directly - instead the event handler(s) get executed when the event is raised.
I'll likely want to use a centralised EventDispatcher. How could I get hold of one?
Pass it in as an argument.
It probably won't look like an EventDispatcher, but instead like some Domain Service that describes the required capability in domain specific terms. When composing the application, you choose which implementation of the service to use.
You are asking to have it both ways. You either need to inject the dependency or invert control and let another object manager the interaction between Aggregate and EventDispatcher. I recommend keeping your Aggregates as simple as possible so that they are free of dependencies and remain testable as well.
The following code sample is very simple and would not be what you put into production, but illustrates how to design Aggregates free of dependencies without passing around a list of events outside of a context that needs them.
If your Aggregate has a list of events within it:
class MyAggregate
{
private List<IEvent> events = new List<IEvent>();
// ... Constructor and event sourcing?
public IEnumerable<IEvent> Events => events;
public string Name { get; private set; }
public void ChangeName(string name)
{
if (Name != name)
{
events.Add(new NameChanged(name);
}
}
}
Then you might have a handler that looks like:
public class MyHandler
{
private Repository repository;
// ... Constructor and dependency injection
public void Handle(object id, ChangeName cmd)
{
var agg = repository.Load(id);
agg.ChangeName(cmd.Name);
repository.Save(agg);
}
}
And a repository that looks like:
class Repository
{
private EventDispatcher dispatcher;
// ... Constructor and dependency injection
public void Save(MyAggregate agg)
{
foreach (var e in agg.Events)
{
dispatcher.Dispatch(e);
}
}
}

Resolve Service Implementation from Autofac based on Runtime Session Value

Need some help trying to solve a problem resolving an implementation of a service at runtime based on a parameter. In other words use a factory pattern with DI.
We have Autofac wired in to our MVC application. I am trying to figure out how we can use a user session variable (Call it Ordering Type) to be used for the Dependency Resolver to resolve the correct implementation of a service.
An example of what we are trying to do.
The application has two "types" of ordering - real eCommerce type of ordering (add stuff to a shopping cart, checkout etc).
The other is called Forecast ordering. Users create orders - but they do not get fulfilled right away. They go through an approval process and then fulfilled.
The bottom line is the data schema and back end systems the application talks to changes based on the order type.
What I want to do is:
I have IOrderManagerService
public interface IOrderManagerService
{
Order GetOrder(int orderNumber);
int CreateOrder(Order order);
}
Because we have two ordering "types" - I have two implementations of the the IOrderManagerService:
public class ShelfOrderManager : IOrderManagerService
{
public Order GetOrder(int orderMumber)
{
...code
}
public int CreateOrder(Order order)
{
...code
}
}
and
public class ForecastOrderManager: IOrderManagerService
{
public Order GetOrder(int orderMumber)
{
...code
}
public int CreateOrder(Order order)
{
...code
}
}
My First question is - in my MVC application - do I register these implementations as?
builder.RegisterType<ShelfOrderManager>().As<IOrderManagerService>();
builder.RegisterType<ForecastOrderManager>().As<IOrderManagerService>();
What we are planning on doing is sticking the user selected ordering type in a users session. When a user wants to view order status - depending on their selected ordering "type" - I need the resolver to give the controller the correct implementation.
public class OrderStatusController : Controller
{
private readonly IOrderManagerService _orderManagerService;
public OrderStatusController(IOrderManagerService orderManagerService)
{
//This needs to be the correct implementation based on the users "type".
_orderManagerService = orderManagerService;
}
public ActionResult GetOrder(int orderNumber)
{
var model = _orderManagerService.GetOrder(orderNumber);
return View(model);
}
}
I've ready about the the delegate factory and this answer explains the concept well.
The problem is the runtime parameters are being used to construct the service and resolve at runtime. i.e.
var service = resolvedServiceClass.Factory("runtime parameter")
All this would do is give me "service" that used the "runtime parameter" in the constructor.
I've looked at Keyed or Named resolution too.
At first I thought I could combine these two techniques - but the controller has the dependency on the interface - not the concrete implementation. (as it should)
Any ideas on how to get around this would be MUCH appreciated.
As it would turn out we were close. #Andrei is on target with what we did. I'll explain the answer below for the next person that comes across this issue.
To recap the problem - I needed to resolve a specific concrete implementation of an interface using Autofac at run time. This is commonly solved by the Factory Pattern - but we already had DI implemented.
The solution was using both. Using the delegate factory Autofac supports, I created a simple factory class.
I elected to resolve the component context privately
DependencyResolver.Current.GetService<IComponentContext>();
versus having Autofac resolve it predominately so I did not have to include IComponentContext in all of my constructors that that will be using the factory.
The factory will be used to resolve the services that are dependent on run time parameters - which means wherever a
ISomeServiceThatHasMultipleImplementations
is used in a constructor - I am going to replace it with ServiceFactory.Factory factory. I did not want to ALSO include IComponentContext wherever I needed the factory.
enum OrderType
{
Shelf,
Forecast
}
public class ServiceFactory : IServiceFactory
{
private readonly IComponentContext _componentContext;
private readonly OrderType _orderType;
public ServiceFactory(OrderType orderingType)
{
_componentContext = DependencyResolver.Current.GetService<IComponentContext>();
_orderType = orderingType;
}
public delegate ServiceFactory Factory(OrderType orderingType);
public T Resolve<T>()
{
if(!_componentContext.IsRegistered<T>())
return _componentContext.ResolveNamed<T>(_orderType.ToString());
return _componentContext.Resolve<T>();
}
}
With the factory written, we also used the Keyed services.
Using my order context -
public interface IOrderManagerService
{
Order GetOrder(int orderNumber);
int CreateOrder(Order order);
}
public class ShelfOrderManager : IOrderManagerService
{
public Order GetOrder(int orderNumber)
{
...
}
public int CreateOrder(Order order)
{
...
}
}
public class ForecastOrderManager : IOrderManagerService
{
public Order GetOrder(int orderNumber)
{
...
}
public int CreateOrder(Order order)
{
...
}
}
The registration of Keyed services:
//register the shelf implementation
builder.RegisterType<ShelfOrderManager>()
.Keyed(OrderType.Shelf)
.As<IOrderManager>();
//register the forecast implementation
builder.RegisterType<ForecastOrderManager>()
.Keyed(OrderType.Shelf)
.As<IOrderManager>();
Register the factory:
builder.RegisterType<IMS.POS.Services.Factory.ServiceFactory>()
.AsSelf()
.SingleInstance();
Finally using it in the controllers (or any other class for that matter):
public class HomeController : BaseController
{
private readonly IContentManagerService _contentManagerService;
private readonly IViewModelService _viewModelService;
private readonly IApplicationSettingService _applicationSettingService;
private readonly IOrderManagerService _orderManagerService;
private readonly IServiceFactory _factory;
public HomeController(ServiceFactory.Factory factory,
IViewModelService viewModelService,
IContentManagerService contentManagerService,
IApplicationSettingService applicationSettingService)
{
//first assign the factory
//We keep the users Ordering Type in session - if the value is not set - default to Shelf ordering
_factory = factory(UIUserSession?.OrderingMode ?? OrderType.Shelf);
//now that I have a factory to get the implementation I need
_orderManagerService = _factory.Resolve<IOrderManagerService>();
//The rest of these are resolved by Autofac
_contentManagerService = contentManagerService;
_viewModelService = viewModelService;
_applicationSettingService = applicationSettingService;
}
}
I want to work out a bit more handling of the Resolve method - but for the first pass this works. A little bit Factory Pattern (where we need it) but still using Autofac to do most of the work.
I would not rely on Autofac for this. IOC is used to resolve a dependency and provide an implementation for it, what you need is to call a different implementation of the same interface based on a decision flag.
I would use a simple factory basically, like a class with 2 static methods and call whichever implementation you need need to when you know what the decision is. This gives you the run-time resolver you are after. Keep it simple I'd say.
This being said it seems there is another option. Have a look at the "select by context" option, maybe you can redesign your classes to take advantage of this: http://docs.autofac.org/en/latest/faq/select-by-context.html

How do you add a runtime string parameter into a dependency resolution chain?

How could I setup my chosen DI for this kind of setup:
public abstract class BaseRepo
{
public BaseRepo(string token)
{
}
}
public RepoA : BaseRepo, IRepoA
{
// implementation of interface here
}
public ViewModelA
{
IRepoA _repo;
public ViewModelA(IRepoA repo)
{
this._repo = repo;
}
public DoMethod()
{
this._repo.DoSomeStuff();
}
}
In real scenario, the token parameter on the base class is resolved after the user has been logged in. I was thinking of just configuring the interfaces for DI after the login but I'm not sure if that a right thing do.
I looked at some Factories but I can't make it to work.
My choice of DI probably goes to AutoFac/Ninject and the project is Xamarin mobile app
In real scenario, the token parameter on the base class is resolved
after the user has been logged in.
This means that the token parameter is runtime data. Prevent injecting runtime data into your components. Your components should be stateless. Instead, runtime data should be passed on through method calls through the previously constructed object graph of components. Failing to do so, will make it much more complicated to configure and verify your object graphs.
There are typically to ways of passing runtime data. Either you pass it on through method calls from method to method through the object graph, or your components call a method that returns that correct value. This token seems like it is contextual information and that would typically mean you choose the latter option:
public interface ITokenProvider {
string GetCurrentToken();
}
// Don't use base classes: base classes are a design smell!
public RepoA : IRepoA
{
private readonly ITokenProvider tokenProvider;
public RepoA(ITokenProvider tokenProvider) {
this.tokenProvider = tokenProvider;
}
// IRepoA methods
public A GetById(Guid id) {
// Get token at runtime
string token = this.tokenProvider.GetCurrentToken();
// Use token here.
}
}
In your Composition Root, you will have to create an implementation for this ITokenProvider. How this implementation looks is highly dependent on how you wish to store this token, but here's a possible implementation:
public sealed class AspNetSessionTokenProvider : ITokenProvider {
public string GetCurrentToken() {
return (string)HttpContext.Current.Session["token"];
}
}

NServiceBus Dependency Injection

I've been having a bit of trouble with this.
Andreas Öhlund answered a question on it here, but I've been unable to get it to work using the advice he gave.
Here's my setup:
public abstract class CommandHandler<T> : IHandleMessages<T>, IDomainReadRepository where T : Command
{
public IDomainRepository DomainRepository { get; set; }
protected abstract void OnProcess(T command);
public TAggregate GetById<TAggregate>(Guid id) where TAggregate : IEventProvider, new()
{
return DomainRepository.GetById<TAggregate>(id);
}
public void Handle(T message)
{
OnProcess(message);
// Domain repository will save.
}
}
The idea is specific command handlers override the OnProcess method and do their thing, then the DomainRepository will save everything.
Here is how I've registered the components:
public class EndpointConfig : IConfigureThisEndpoint, AsA_Server, IWantCustomInitialization
{
public void Init()
{
Configure.With().DefiningCommandsAs(c => c.Namespace != null && c.Namespace.EndsWith("Commands"));
Configure.Instance.DefaultBuilder().Configurer.ConfigureComponent<DomainRepository>(DependencyLifecycle.InstancePerCall);
Configure.Instance.DefaultBuilder().Configurer.ConfigureComponent<EventStore.Sql.EventStore>(DependencyLifecycle.InstancePerCall);
Configure.Instance.DefaultBuilder().Configurer.ConfigureComponent<MongoDbObjectSecurityDescriptorRepository>(DependencyLifecycle.InstancePerCall);
Configure.Instance.DefaultBuilder().Configurer.ConfigureComponent<LocalTenantConfig>(DependencyLifecycle.InstancePerCall);
}
}
Those are all the objects down the chain that are used by the DomainRepository; however, when I receive a command, the DomainRepository is null. If I comment out the lines to register the objects that DomainRepository needs, I'll actually get an error saying it failed to create it (Autofac DependencyResolutionException).
It should be noted that all the other objects use constructor injection (they're taken from a previously existing project). I tried changing them to use public property injection, but it didn't make any difference.
It would be much appreciated if somebody could point out what I'm doing wrong here!
Move the code in your init method into a different class which implements INeedInitialization. In there, use Configure.Instance instead of Configure.With() and also instead of Configure.Instance.DefaultBuilder().

Resources