Created
February 18, 2014 15:54
-
-
Save lmauri/9073631 to your computer and use it in GitHub Desktop.
Autofac manual dependency resolver
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Inject the IComponentContext in the property of every BaseController | |
In BaseController I'll use IComponentContext to resolve services that are non singleton(i.e. datacontext dependency that | |
use per request lifetime scope) | |
*/ | |
static void SetDependencyResolverAndConfig(Action<ContainerBuilder> config) | |
{ | |
var builder = new ContainerBuilder(); | |
builder.RegisterApiControllers(Assembly.GetExecutingAssembly()) | |
.OnActivated((e) => | |
{ | |
if (e.Instance is BaseController) | |
{ | |
(e.Instance as BaseController).IocContext = e.Context.Resolve<IComponentContext>(); | |
} | |
}); | |
config(builder); | |
var container = builder.Build(); | |
var resolver = new AutofacWebApiDependencyResolver(container); | |
GlobalConfiguration.Configuration.DependencyResolver = resolver; | |
} | |
/* | |
In the BaseController I'll use IocContext to resolve any dependency registered with the Autofac container, | |
even the per-request dependencies. | |
*/ | |
public class BaseController : ApiController | |
{ | |
public Autofac.IComponentContext IocContext { get; set; } | |
protected Data.User CurrentUser | |
{ | |
get | |
{ | |
if (_currentUser == null) | |
{ | |
var service = this.IocContext.Resolve<UserService>(); | |
_currentUser = service.GetUserByGuid(this.CurrentIdentity.Guid); | |
} | |
return _currentUser; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment