Skip to content

Commit

Permalink
Fix to make scoped dependencies work in router.
Browse files Browse the repository at this point in the history
  • Loading branch information
gautema committed Sep 18, 2017
1 parent b196157 commit 6b469d3
Showing 1 changed file with 26 additions and 5 deletions.
31 changes: 26 additions & 5 deletions Sample/CQRSWeb/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
using System.Linq;
using CQRSlite.Messages;
using CQRSlite.Routing;
using Microsoft.AspNetCore.Http;
using ISession = CQRSlite.Domain.ISession;

namespace CQRSWeb
{
Expand All @@ -29,10 +31,10 @@ public IServiceProvider ConfigureServices(IServiceCollection services)
services.AddSingleton<ICommandSender>(y => y.GetService<Router>());
services.AddSingleton<IEventPublisher>(y => y.GetService<Router>());
services.AddSingleton<IHandlerRegistrar>(y => y.GetService<Router>());
services.AddScoped<ISession, Session>();
services.AddSingleton<IEventStore, InMemoryEventStore>();
services.AddScoped<ICache, MemoryCache>();
services.AddSingleton<ICache, MemoryCache>();
services.AddScoped<IRepository>(y => new CacheRepository(new Repository(y.GetService<IEventStore>()), y.GetService<IEventStore>(), y.GetService<ICache>()));
services.AddScoped<ISession, Session>();

services.AddTransient<IReadModelFacade, ReadModelFacade>();

Expand All @@ -48,13 +50,12 @@ public IServiceProvider ConfigureServices(IServiceCollection services)
.AsSelf()
.WithTransientLifetime()
);

// Add framework services.
services.AddMvc();

//Register router
//Register routes
var serviceProvider = services.BuildServiceProvider();
var registrar = new RouteRegistrar(serviceProvider);
var registrar = new RouteRegistrar(new Provider(serviceProvider));
registrar.Register(typeof(InventoryCommandHandlers));

return serviceProvider;
Expand All @@ -74,4 +75,24 @@ public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerF
});
}
}


//This makes scoped services work inside router.
public class Provider : IServiceProvider
{
private readonly ServiceProvider _serviceProvider;
private readonly IHttpContextAccessor _contextAccessor;

public Provider(ServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
_contextAccessor = _serviceProvider.GetService<IHttpContextAccessor>();
}

public object GetService(Type serviceType)
{
return _contextAccessor?.HttpContext?.RequestServices.GetService(serviceType) ??
_serviceProvider.GetService(serviceType);
}
}
}

0 comments on commit 6b469d3

Please sign in to comment.