Autofac Issue: Cannot resolve parameter of constructor 'Void .ctor - c#

My .Net 7 application has the following issue:
Autofac.Core.DependencyResolutionException: An exception was thrown while activating MyApp.Modules.MyModule.Application.MyModule.UpdateCommand.UpdateCommandHandler.
---> Autofac.Core.DependencyResolutionException: None of the constructors found with 'MyApp.Modules.MyModule.Infrastructure.Configuration.AllConstructorFinder' on type 'MyApp.Modules.MyModule.Application.MyModule.UpdateCommand.UpdateCommandHandler' can be invoked with the available services and parameters:
Cannot resolve parameter 'MyApp.Modules.MyModule.Application.Contracts.IMyModule myModule' of constructor 'Void .ctor(Serilog.ILogger, MyApp.Modules.MyModule.Application.Contracts.IMyModule)'.
UpdateCommandHandler.cs (where the issue is occurring)
public class UpdateCommandHandler: ICommandHandler<UpdateCommand>
{
private readonly IMyModule _myModule;
private readonly ILogger _logger;
public UpdateCommandHandler(ILogger logger, IMyModule myModule)
{
_myModule = myModule;
_logger = logger;
}
public async Task<Unit> Handle(UpdateCommand request, CancellationToken cancellationToken)
{
var foo = await _myModule.ExecuteQueryAsync(new SampleQuery());
return Unit.Value;
}
}
Program.cs
...
var builder = WebApplication.CreateBuilder(args);
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
builder.Host.ConfigureContainer<ContainerBuilder>(b => b.RegisterModule(new AutofacModules()));
...
I looked at similar issues before posting, such as this, but I do believe I appropriately registered IMyModule in Autofac as MyModule in the following.
AutofacModules.cs
public class AutofacModules: Autofac.Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType<MyModule>().As<IMyModule>().InstancePerLifetimeScope();
}
}
IMyModule.cs
public interface IMyModule
{
Task ExecuteCommandAsync(ICommand command);
Task<TResult> ExecuteQueryAsync<TResult>(IQuery<TResult> query);
}
MyModule.cs
public class MyModule: IMyModule
{
public async Task ExecuteCommandAsync(ICommand command)
{
await CommandsExecutor.Execute(command);
}
public Task<TResult> ExecuteQueryAsync<TResult>(IQuery<TResult> query)
{
var scope = MyCompositionRoot.BeginLifetimeScope();
var mediator = scope.Resolve<IMediator>();
return mediator.Send(query);
}
}
AllConstructorFinder.cs
internal class AllConstructorFinder : IConstructorFinder
{
private static readonly ConcurrentDictionary<Type, ConstructorInfo[]> Cache = new();
public ConstructorInfo[] FindConstructors(Type targetType)
{
var result = Cache.GetOrAdd(targetType, t => t.GetTypeInfo().DeclaredConstructors.ToArray());
return result.Length > 0 ? result : throw new NoConstructorsFoundException(targetType);
}
}

In my Program.cs, I had registered MyModule, but, as I have multiple modules with their own containers, I didn't register it in the module's own composition root. By adding the following line, I'm able to include MyModule as a constructor parameter.
MyModuleStartup.cs
...
var containerBuilder = new ContainerBuilder();
...
/* NEW LINE */
containerBuilder.RegisterType<CventModule>().As<ICventModule>().InstancePerLifetimeScope();
...
So lesson here is make sure the component you are using is registered to Autofac root container your module is running directly in. Thanks to #Travis Illig for the troubleshooting link which helped me immensely.

Related

C# MediatR error: Register your handlers with the container

Every time that i try to call Send from MediatR to any Query/Command that i have, it returns this Exception:
System.InvalidOperationException: 'Error constructing handler for request of type MediatR.IRequestHandler2[CQRSHost.Recursos.Queries.GetTodosProdutosQuery,System.Collections.Generic.IEnumerable1[CQRSHost.Models.Produto]]. Register your handlers with the container. See the samples in GitHub for examples.'
Inner Exception:
InvalidOperationException: Cannot resolve 'MediatR.IRequestHandler2[CQRSHost.Recursos.Queries.GetTodosProdutosQuery,System.Collections.Generic.IEnumerable1[CQRSHost.Models.Produto]]' from root provider because it requires scoped service 'CQRSHost.Context.AppDbContext'.
But i have the AppDbContext in my DI container:
public static IHostBuilder CreateHostBuilder(string[] args)
{
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
return Host.CreateDefaultBuilder(args)
.UseSerilog()
.UseEnvironment("Development")
.ConfigureHostConfiguration(hostConfig =>
{
hostConfig.SetBasePath(Directory.GetCurrentDirectory());
hostConfig.AddEnvironmentVariables("DSO_");
})
.ConfigureServices((context, services) =>
{
services.AddSingleton(ConfigureLogger());
services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(
"Server=localhost;Database=newdatabase;User Id=sa;Password=P#ssw0rd!##$%;",
b => b.MigrationsAssembly(typeof(AppDbContext).Assembly.FullName)));
services.AddHostedService<NewService>();
//services.AddMediatR(Assembly.GetExecutingAssembly());
//services.AddMediatR(typeof(GetTodosProdutosQuery).GetTypeInfo().Assembly);
services.AddMediatR(AppDomain.CurrentDomain.GetAssemblies());
});
}
Here is the service that i use to call the query:
public class NewService : IHostedService
{
private readonly ILogger _logger;
private readonly IMediator _mediator;
public NewService(ILogger logger, IMediator mediator)
{
_logger = logger;
_mediator = mediator;
}
public async Task StartAsync(CancellationToken cancellationToken)
{
var command = new GetTodosProdutosQuery();
var response = await _mediator.Send(command);
_logger.Information($"First Name: {response.First()?.Nome}");
}
public Task StopAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
}
And here is what my project looks like:
ProjectImage
The commented lines is what i've already tryied to solve.
What am i doing wrong?
The exception "Register your handlers with the container." is misleading. The real error is described in the inner exception:
Cannot resolve 'MediatR.IRequestHandler<GetTodosProdutosQuery, IEnumerable>' from root provider because it requires scoped service 'CQRSHost.Context.AppDbContext'.
This happens because you inject the IMediator into a singleton consumer NewService. The Mediator implementation depends on a IServiceProvider but as NewService is singleton, it is resolved from the root container, and so will all its dependencies recursively. This means that once Mediator starts resolving from its IServiceProvider, it also resolves from the root container. And scoped services can't be resolved from the root container, because that would lead to bugs, because that scoped service would be cached for the lifetime of the root container, and reused for the lifetime of the root container - which means indefinitely.
The solution is to inject an IServiceScope into NewService create a scope from within its StartAsync and resolve the IMediator from there:
public class NewService : IHostedService
{
private readonly IServiceProvider _container;
public NewService(IServiceProvider container)
{
_container = container;
}
public async Task StartAsync(CancellationToken cancellationToken)
{
await using (var scope = _container.CreateScope())
{
var logger = scope.ServiceProvider.GetRequiredService<ILogger>();
var mediator = scope.ServiceProvider.GetRequiredService<IMediator>();
var command = new GetTodosProdutosQuery();
var response = await mediator.Send(command);
logger.Information($"First Name: {response.First()?.Nome}");
}
}
...
}
Another, perhaps more convenient option would be to ensure that the mediator always resolves from a new scope. This can be achieved using the following code:
public record ScopedSender<TSender>(IServiceProvider Provider)
: ISender where TSender : ISender
{
public Task<TResponse> Send<TResponse>(
IRequest<TResponse> request, CancellationToken ct)
{
async using (var scope = Provider.CreateScope());
var sender = scope.ServiceProvider.GetRequiredService<TSender>();
return await sender.Send(request, ct);
}
public Task<object?> Send(object request, CancellationToken ct)
{
async using (var scope = Provider.CreateScope());
var sender = scope.ServiceProvider.GetRequiredService<TSender>();
return await sender.Send(request, ct);
}
public IAsyncEnumerable<TResponse> CreateStream<TResponse>(
IStreamRequest<TResponse> request, CancellationToken ct)
{
async using (var scope = Provider.CreateScope());
var sender = scope.ServiceProvider.GetRequiredService<TSender>();
return await sender.CreateStream(request, ct);
}
public IAsyncEnumerable<object?> CreateStream(object request, CancellationToken ct)
{
async using (var scope = Provider.CreateScope());
var sender = scope.ServiceProvider.GetRequiredService<TSender>();
return await sender.CreateStream(request, ct);
}
}
Now configure this as follows:
services.AddMediatR(AppDomain.CurrentDomain.GetAssemblies());
services.AddTransient<Mediator>();
services.AddSingleton<ISender, ScopedSender<Mediator>>();
Now you can safely inject your ISender into yout NewService without having to apply scoping:
public class NewService : IHostedService
{
private readonly ILogger _logger;
private readonly IMediator _sender;
public NewService(ILogger logger, ISender sender)
{
_logger = logger;
_sender = sender;
}
public async Task StartAsync(CancellationToken cancellationToken)
{
var command = new GetTodosProdutosQuery();
var response = await _sender.Send(command);
_logger.Information($"First Name: {response.First()?.Nome}");
}
public Task StopAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
}
I was having the same problem, I solved it here by changing AddScoped to AddSingleton and adding builder.Services.AddTransient();

DI for class not resolving in Function

I have set up DI for an Azure function but it will not resolve when I run the function. The code I have is:
StartUp:
[assembly: FunctionsStartup(typeof(OmegaConnector.StartUp))]
namespace OmegaConnector
{
public class StartUp : FunctionsStartup
{
public override void Configure(IFunctionsHostBuilder builder)
{
var config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables()
.Build();
builder.Services.AddLogging();
builder.Services.AddVehicleSearchCosmosDataProvider();
builder.Services.AddScoped<IProcessSearchData, SearchProcessor>(); <- This one
}
}
IProcessSearchData:
public interface IProcessSearchData
{
Task<bool> ProcessData(string campaign);
}
SearchProcessor:
public class SearchProcessor : IProcessSearchData
{
public async Task<bool> ProcessData(string campaign)
{
return true;
}
}
Function:
public OmegaConnectorFunction(ILogger<OmegaConnectorFunction> logger, IProcessSearchData searchProcessor)
{
I get the error:
Executed 'CatchCampaign' (Failed, Id=daef3371-fa4d-4d1f-abad-7ad343537872)
[27/05/2020 12:17:27] Microsoft.Extensions.DependencyInjection.Abstractions: Unable to resolve service for type 'OmegaConnector.Interfaces.IProcessSearchData' while attempting to activate 'OmegaConnector.OmegaConnectorFunction'.
Sorry if this is too simple but I just can't see what I have wrong here. I think I have this set up correctly but I obviously don't. Can anyone see what I need to do?
See here: https://learn.microsoft.com/en-us/azure/azure-functions/functions-dotnet-class-library
The Functions 3.x packages are built with .NET Core 3.1 in mind.
Try keeping these versions in sync so there are no dependency compatibility problems.
From what I understood of the documentation provided by Microsoft the issue may be that the service needs to be injected into the class that contains the function.
I'm unsure if this is what you've done from the code examples you've provided. An example of this is:
public class OmegaConnectorFunction
{
private readonly ILogger _logger;
private readonly IProcessSearchData _searchProcessor;
public OmegaConnectorFunction(ILogger<OmegaConnectorFunction> logger, IProcessSearchData searchProcessor)
{
_logger = logger;
_searchProcessor = searchProcessor;
}
[FunctionName("OmegaConnectorFunction")]
public async Task<IActionResult> Run([HttpTrigger] HttpRequest request)
{
var campaign = await request.Content.ReadAsAsync<string>();
_searchProcessor.ProcessData(campaign);
return new OkResult();
}
}
public class OmegaConnectorFunction {
private readonly IProcessSearchData _searchProcessor;
public OmegaConnectorFunction(IProcessSearchData searchProcessor)
{
_searchProcessor = searchProcessor;
}
[FunctionName("OmegaConnectorFunction")]
public async Task<IActionResult> Run([HttpTrigger] HttpRequest request, ILogger log) // ILogger is automatically imported
{
var campaign = await request.Content.ReadAsAsync<string>();
_searchProcessor.ProcessData(campaign);
return new OkResult();
}
}

Why Autofac can't resolve this dependency?

The error message I'm getting is
2016-09-14 18:55:12,276 INFO
NServiceBus.Unicast.Transport.TransportReceiver - Failed to process
message Autofac.Core.DependencyResolutionException: None of the
constructors found with
'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type
'ProjectServices.EsbHandlers.NewProcessMessageHandler' can be invoked
with the available services and parameters: Cannot resolve parameter
'ProjectServices.Cache.ICachedNotificationsStorage
cachedNotificationsStorage' of constructor 'Void
.ctor(Project.Model.IRepository,
Project.Model.Services.ICaseDelegationService,
Priject.Model.Services.IDocumentDelegationService,
ETeismasServices.Cache.ICachedNotificationsStorage)'.
The dependency is registered in Autofac :
builder.RegisterType<CachedNotificationsStorage>().As<ICachedNotificationsStorage>();
And this is the CachedNotificationStorage constructor
public class CachedNotificationsStorage : ICachedNotificationsStorage
{
private readonly int itemsExpireMinutes;
private const string NotificationsCacheKey = "Notifications";
private readonly ObjectCache cache;
public CachedNotificationsStorage()
{
itemsExpireMinutes = int.Parse(ConfigurationManager.AppSettings["notificationsListItemsCahceExpirationInMinutes"]);
cache = MemoryCache.Default;
cache.Add(NotificationsCacheKey, new List<CachedNotificationsListItem>(), new CacheItemPolicy());
}
//.... logic etc
}
So Autofac is trying to create a NewProcessMessageHandler
For that, Autofac needs to resolve an implementation of ICachedNotificationStorage.
There is a concrete implementation of ICachedNotificationStorage registered as ICachedNotificationStorage.
Why can't Autofac resolve it?
There is no magic in that constructor, it just adds an initial empty list to the cache.
NewProcessMessageHandler class :
public class NewProcessMessageHandler : BaseHandler<NewProcessMessage>
{
public NewProcessMessageHandler(IRepository repository, ICaseDelegationService caseDelegationService,
IDocumentDelegationService documentDelegationService, ICachedNotificationsStorage cachedNotificationsStorage)
: base(repository, caseDelegationService, documentDelegationService, cachedNotificationsStorage)
{
}
}
And its base
public abstract class BaseHandler<T>: IHandleMessages<T>
{
...
protected BaseHandler(IRepository repository, ICaseDelegationService caseDelegationService,
IDocumentDelegationService documentDelegationService, ICachedNotificationsStorage cachedNotificationsStorage)
{
this.repository = repository;
this.caseDelegationService = caseDelegationService;
this.documentDelegationService = documentDelegationService;
this.cachedNotificationsStorage = cachedNotificationsStorage;
}
...
}
Full code which performs the registration
private void StartNserviceBus()
{
SetLoggingLibrary.Log4Net(() => log4net.Config.XmlConfigurator.Configure());
Configure.Transactions.Enable();
Configure.Serialization.Xml();
var builder = Behaviors.IoCServiceBehavior.CreateContainerBuilder();
builder.RegisterType<Repository>().As<IRepository>()
.WithResolvedParameter((c, p) => new Lazy<ISession>(() => SessionFactory.Get().OpenSession()));
builder.RegisterType<CaseDelegationService>().As<ICaseDelegationService>();
builder.RegisterType<DocumentDelegationService>().As<IDocumentDelegationService>();
builder.RegisterType<ChargesServiceStub>().As<IProjectChargesService>();
builder.RegisterType<CachedNotificationsStorage>().As<ICachedNotificationsStorage>();
builder.RegisterType<MeowDataOutputServiceClient>().As<IMeowDataOutputService>().AsWcfProxy();
RegisterESBMessageHandlers(builder);
container = builder.Build();
Configure.With(AllAssemblies.Matching("ExternalServices.Contracts.ESB.").And("ProjectService"))
.DefineEndpointName("project_inbound")
.AutofacBuilder(container)
.UseTransport<Msmq>()
.MsmqSubscriptionStorage()
.DisableTimeoutManager()
.PurgeOnStartup(false)
.UnicastBus()
.ImpersonateSender(false)
.LoadMessageHandlers()
.DisableTimeoutManager()
#if DEBUG
.Log4Net()
#endif
.DefiningEventsAs(t => t.Namespace != null && t.Namespace.StartsWith("ExternalServices.Contracts.ESB"))
.CreateBus()
.Start(
() => Configure.Instance.ForInstallationOn<NServiceBus.Installation.Environments.Windows>().Install()
);
}
RegisterESBMEssageHanlders() : the method registers 40+ message handlers
private void RegisterESBMessageHandlers(ContainerBuilder builder)
{
...40 of them handlers
builder.RegisterType<EsbHandlers.NewPartyDocumentMessageHandler>().AsSelf();
builder.RegisterType<EsbHandlers.NewProcessMessageHandler>().AsSelf();
}

How to reuse an InstancePerRequest instance create in composition root using Autofac

I have an Asp.NET MVC5 application in which I registre my types using Autofac in Startup class in this way:
public class Startup
{
public void Configuration(IAppBuilder app)
{
IContainer container = null;
var builder = new ContainerBuilder();
// Register Services
builder.RegisterType<SalesRepository>().As<ISalesRepository>().InstancePerRequest();
builder.RegisterType<SalesService>().As<ISalesService>().InstancePerRequest();
builder.RegisterAssemblyTypes(AppDomain.CurrentDomain.GetAssemblies())
.AsClosedTypesOf(typeof(IHandle<>))
.AsImplementedInterfaces()
.InstancePerRequest();
builder.Register<IAppEvents>(_ => new AppEvents(container)).InstancePerRequest();
// Register MVC Controllers
builder.RegisterControllers(Assembly.GetExecutingAssembly());
container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
app.UseAutofacMiddleware(container);
app.UseAutofacMvc();
}
}
These are my services (this is a simplified scenario, only for demonstration).
The SalesService class receives a ISalesRepository interface as dependency . In addition I have an AppEvents class where I want to resolve IHandle types:
public interface ISalesRepository { }
public class SalesRepository : ISalesRepository
{
public SalesRepository() { }
}
public interface ISalesService { }
public class SalesService : ISalesService
{
ISalesRepository _repo;
public SalesService(ISalesRepository repo)
{
_repo = repo;
}
}
public interface IHandle<T>
{
void Handle();
}
public class SalesActionHandle : IHandle<string>
{
ISalesRepository _repo;
public SalesActionHandle(ISalesRepository repo)
{
_repo = repo;
}
public void Handle() { }
}
public interface IAppEvents
{
void Raise<T>();
}
public class AppEvents : IAppEvents
{
private readonly IContainer _container;
public AppEvents(IContainer container)
{
if (container == null)
throw new ArgumentNullException("container");
_container = container;
}
public void Raise<T>()
{
var handlers = _container.Resolve<IEnumerable<IHandle<T>>>(); // Runtime error here
foreach (var handler in handlers)
handler.Handle();
}
}
And this is my only (simplified) controller:
public class HomeController : Controller
{
ISalesService _service;
IAppEvents _events;
public HomeController(ISalesService service, IAppEvents events)
{
_service = service;
_events= events;
}
public ActionResult Index()
{
_events.Raise<string>();
return View();
}
}
The problem I have is that I get an error at this line when it is executed:
var handlers = _container.Resolve<IEnumerable<IHandle<T>>>();
No scope with a Tag matching 'AutofacWebRequest' is visible from the scope in which the instance was requested. This generally indicates that a component registered as per-HTTP request is being requested by a SingleInstance() component (or a similar scenario.) Under the web integration always request dependencies from the DependencyResolver.Current or ILifetimeScopeProvider.RequestLifetime, never from the container itself.
I resolve it by doing this:
public void Raise<T>()
{
using (var scope = _container.BeginLifetimeScope("AutofacWebRequest"))
{
var handlers = scope.Resolve<IEnumerable<IHandle<T>>>();
foreach (var handler in handlers)
handler.Handle();
}
}
But in this case, when IHandle is resolved (with SalesActionHandle instance), a new instance of SalesRepository is passed as parameter in SalesActionHandle constructor. What I want is to "reuse" the same instance that SalesService is using (it was created when ISalesService was resolved. I want the same SalesRepository instance for the request)
Is there any way to achieve this behaviour?
The sample code is avaible in Github: https://github.com/josmonver/AutofacTest
You may want to use
AutofacDependencyResolver.Current.RequestLifetimeScope
to match your current request scope, but not to create a new request scope.

Resolving dbcontext per request with Unity in WebApi

I am struggling to make this work. I've got Unity and Unity.AspNet.WebApi packages (v 3.5.1404) installed and below activation code which came with the packages
public static class UnityWebApiActivator
{
/// <summary>Integrates Unity when the application starts.</summary>
public static void Start()
{
var container = UnityConfig.GetConfiguredContainer();
var resolver = new UnityHierarchicalDependencyResolver(container);
GlobalConfiguration.Configuration.DependencyResolver = resolver;
// DynamicModuleUtility.RegisterModule(typeof(UnityPerRequestHttpModule));
}
/// <summary>Disposes the Unity container when the application is shut down.</summary>
public static void Shutdown()
{
var container = UnityConfig.GetConfiguredContainer();
container.Dispose();
}
}
and my type registration looks like this:
public static void RegisterTypes(IUnityContainer container)
{
container.RegisterType<IAuditService, AuditService>(
new PerThreadLifetimeManager(),
new InjectionConstructor(new SecurityDbContext()));
}
So far I've tried PerThreadLifetimeManager and TransientLifetimeManager with no success. I've also got the Unity.Mvc package and tried using the PerRequestLifetimeManager as suggested by msdn but no luck. It always gives me the same instance of dbcontex.
I rather do not include any MVC dependency as this is purely WebApi but when I try to use Unity.Mvc, I ended up some http runtime errors too.
Anyone has a good suggestion/example to resolve dbcontext per request with Unity in WebApi, preferably without any mvc dependency?
The way I was injecting db context was the problem here. Unity remembers the instance created and injects the same instance for all new AuditService instance created. I simply needed to resolve the db context as below.
container.RegisterType<DbContext, SecurityDbContext>(new PerThreadLifetimeManager());
PerThreadLifetimeManager did the work and it should be fine considering each web requests will be served by a different thread.
I managed to resolve per request by declaring my custom UnityResolver's class within the WebApiConfig class. The UnityResolver class uses the HttpConfiguration class assuming you're using an OWIN context.
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
var _container = new UnityContainer();
DependencyConfiguration.ConfigureContainer(_container);
config.DependencyResolver = new UnityResolver(_container);
}
The ConfigureContainer class is simply a class where I declare my IOC dependencies as shown below:
private static void RegisterReleaseEnv(IUnityContainer container)
{
//Repository Registration
container
.RegisterType(typeof(IRepository<>), typeof(GenericRepository<>), new HierarchicalLifetimeManager());
}
It is very important that you use the HierarchicalLifetimeManager lifetime manager so that you get a new instance per request.
The UnityResolver class then looks like this:
public class UnityResolver : IDependencyResolver
{
protected IUnityContainer container;
public UnityResolver(IUnityContainer container)
{
if (container == null)
{
throw new ArgumentNullException("container");
}
this.container = container;
}
public object GetService(Type serviceType)
{
try
{
return container.Resolve(serviceType);
}
catch (ResolutionFailedException)
{
return null;
}
}
public IEnumerable<object> GetServices(Type serviceType)
{
try
{
return container.ResolveAll(serviceType);
}
catch (ResolutionFailedException)
{
return new List<object>();
}
}
public IDependencyScope BeginScope()
{
var child = container.CreateChildContainer();
return new UnityResolver(child);
}
public void Dispose()
{
container.Dispose();
}
}
I then get a new DB Context using a Generic Repistory as shown below:
public class GenericRepository<TEntity> : IRepository<TEntity>, IDisposable where TEntity : class
{
internal BackendContainer context;
internal DbSet<TEntity> dbSet;
public GenericRepository(BackendContainer context)
{
this.context = context;
this.dbSet = context.Set<TEntity>();
}
public GenericRepository()
: this(new BackendContainer())
{
}
public virtual IQueryable<TEntity> All()
{
return dbSet.AsQueryable();
}
}
Because of the Unity Resolver, the Generic Repository is instantiated per request and so is the DbContext (BackendContainer).
I hope this helps.
For more information: http://www.asp.net/web-api/overview/advanced/dependency-injection

Categories

Resources