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

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.

Related

Correct way to use Autofac with Factory Pattern?

IN a Winforms project, I have set up Autofac and Factory Pattern and it looks like it's working as expected. However, I'm still not sure whether the following is best practice.
The factory class is:
public static class Client
{
public static readonly IRequestFactory RequestFactory = new RequestFactory();
}
public class Configuration
{
public IContainer Container { get; private set; }
public Configuration()
{
var builder = new ContainerBuilder();
builder.RegisterAssemblyTypes(AppDomain.CurrentDomain.GetAssemblies())
.Where(t => t.Name.EndsWith("Request"))
.AsImplementedInterfaces()
.InstancePerLifetimeScope();
Container = builder.Build();
}
}
public class RequestFactory : IRequestFactory, IDisposable
{
private ILifetimeScope scope;
public RequestFactory()
{
scope = Client.Configuration.Container.BeginLifetimeScope();
}
public T Get<T>()
{
return scope.Resolve<T>();
}
public void Dispose()
{
if (scope != null)
{
scope.Dispose();
}
}
}
Then, classes in separate assemblies have the IRequestFactory as a ctor parameter.
Is the above the correct way to implement factor pattern with Autofac or is there a better way?

Autofac: Type 'MyController' does not have a default constructor

I have a Web Api app that consumes another REST Api client. I wrapped the REST API client into a service.
myproj/services/PostDataService.cs
public interface IPostDataService
{
Task<IList<Post>> GetAllPosts();
}
public class PostDataService : IPostDataService
{
private static IDataAPI NewDataAPIClient()
{
var client = new DataAPI(new Uri(ConfigurationManager.AppSettings["dataapi.url"]));
return client;
}
public async Task<IList<Post>> GetAllPosts()
{
using (var client = NewDataAPIClient())
{
var result = await client.Post.GetAllWithOperationResponseAsync();
return (IList<Post>) result.Response.Content;
}
}
}
....
I am using AutoFac and injecting the service in the controller
myproj/controllers/PostController.cs
public class PostController : ApiController
{
private readonly IPostDataService _postDataService;
public PostController(IPostDataService postDataService)
{
_postDataService = postDataService;
}
public async Task<IEnumerable<Post>> Get()
{
return await _postDataService.GetAllPosts();
}
}
But I am getting this error.
An error occurred when trying to create a controller of type
'PostController'. Make sure that the controller has a parameterless
public constructor.
Here is my Global.asax.cs
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
ContainerConfig.Configure();
GlobalConfiguration.Configure(WebApiConfig.Register);
}
}
public static class ContainerConfig
{
private static IContainer _container;
public static IContainer GetContainer()
{
if (_container != null)
return _container;
var builder = new ContainerBuilder();
builder.RegisterType<PostDataService>()
.AsSelf()
.InstancePerLifetimeScope()
.AsImplementedInterfaces();
_container = builder.Build();
return _container;
}
public static IContainer Configure()
{
var container = GetContainer();
var webApiResolver = new AutofacWebApiDependencyResolver(container);
GlobalConfiguration.Configuration.DependencyResolver = webApiResolver;
return container;
}
Can someone spot what I am missing here?
Thanks
I'm missing
builder.RegisterApiControllers(typeof(PostController).Assembly).
Apparently, the controller also needs to be registered.

Convert unity to autofac

I am trying to convert an example piece of code I found on caching with a repository. The only problem is it's using unity for its DI and I don't have any understanding how it works.
public interface IUnitOfWork : IDisposable
{
IRepository<Blog> BlogRepository { get; }
Task<int> SaveChangesAsync();
}
public class UnitOfWork : IUnitOfWork
{
private IDataStoreContext dataStoreContext;
private readonly IUnityContainer container;
public IRepository<Blog> BlogRepository
{
get
{
// TODO : Use unity containers to generate the UnitOfwork so that to make surethat
// datacontext is a single instance in that instance of uow
return new GenericRepository<Blog>(
this.container.Resolve<ICacheStrategy<Blog>>(),
new SqlDataStoreStrategy<Blog>(this.dataStoreContext));
}
}
public UnitOfWork(IDataStoreContext dataStoreContext, IUnityContainer container)
{
this.dataStoreContext = dataStoreContext;
this.container = container;
}
public async Task<int> SaveChangesAsync()
{
return await this.dataStoreContext.SaveChangesAsync();
}
public void Dispose()
{
this.dataStoreContext.Dispose();
}
}
Can anyone point me in the right direction on how I should write this as an autofac statement?
I have only really ever need to use basic autofac e.g.
var builder = new ContainerBuilder();
// Create the container and use the default application services as a fallback
AutofacRegistration.Populate(builder, services);
builder.Register(c => new Logger())
.As<ILogger>()
.InstancePerLifetimeScope();

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

How do I specify which registration of an interface to use with a particular mvc controller?

I have two implementations of an interface that in plain old c# would be instantiated like so:
var useCache = bool.Parse(ConfigurationManager.AppSettings["useCache"]);
var oven = useCache
? new CachedCookieOven(new CookieOven())
: new CookieOven();
var controller = new CookieController(oven); // MVC Controller
here is the interface and classes:
public interface ICookieOven {
IEnumerable<Cookie> Bake();
}
public class CookieOven : ICookieOven {
public IEnumerable<Cookie> Bake() {
var list = new List<Cookie>();
// bake cookies and return them
return list;
}
}
public class CachedCookieOven : ICookieOven {
readonly ICookieOven _oven;
public CachedCookieOven(ICookieOven oven) { _oven = oven; }
public IEnumerable<Cookie> Bake() {
var cookies = GetFromPlate();
return cookies ?? _oven.Bake();
}
}
My MVC controller has the following constructor
public class CookieController : Controller {
readonly ICookieOven _oven;
public CookieController(ICookieOven oven) { _oven = oven; }
public ActionResult ViewCookies() {
var bakedCookies = _oven.Bake();
return View(bakedCookies);
}
}
The Bootstrapper class that is created says in the comments that I don't need to register my mvc controller classes
public static class Bootstrapper
{
public static IUnityContainer Initialise()
{
var container = BuildUnityContainer();
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
return container;
}
private static IUnityContainer BuildUnityContainer()
{
var container = new UnityContainer();
// register all your components with the container here
// it is NOT necessary to register your controllers
// e.g. container.RegisterType<ITestService, TestService>();
RegisterTypes(container);
return container;
}
public static void RegisterTypes(IUnityContainer container)
{
}
}
In Unity I have registered both instances. There may be a better way and if so tell me.
public static class Bootstrapper {
// ...
private static IUnityContainer BuildUnityContainer() {
var container = new UnityContainer();
var useCache = bool.Parse(ConfigurationManager.AppSettings["useCache"]);
// register
container.RegisterType<ICookieOven, CookieOven>("oven");
if (useCache) {
container.RegisterType<ICookieOven, CachedCookieOven>("cachedOven",
new InjectionConstructor(container.Resolve<ICookieOven>("oven"));
}
}
}
How do I ensure that the correct instance of ICookieOven gets sent to the constructor of the CookieController mvc controller?
Registering types in Unity without a name makes that the default type. If you want to register more than one type, you have to provide a name. The following is the correct way to register my types in the Bootstrapper class:
public static void RegisterTypes(IUnityContainer container)
{
var useCache = bool.Parse(ConfigurationManager.AppSettings["useCache"]);
if (useCache) {
// named, this is not the default
container.RegisterType<ICookieOven,CookieOven>("oven");
// this one is not named and is the default
container.RegisterType<ICookieOven,CachedCookieOven>(new InjectionConstructor(
container.Resolve<ICookieOven>("oven"));
} else {
// notice it is not named, it is the default
container.RegisterType<ICookieOven,CookieOven>();
}
}
You want to create an object but which one depends on a value only known at runtime. What you need is a factory (couple of examples here).
To implement this, one approach could be like this: your controller could depend on a IOvenFactory, injected in controller's constructor. When you need the oven you can call _ovenFactory.Create().
In an IOvenFactory implementation, you could have the logic of how to create, depending on the configuration value.

Categories

Resources