Rectangle 27 79

It is certainly possible to configure Autofac to work with both MVC and Web API. This is expected to be a very common scenario. There are two separate dependency resolver implementations because MVC and Web API can be used independently of one another. The same applies for the Autofac integrations.

When using both MVC and Web API in the same application each will require its own dependency resolver, though they can be provided with the same instance of the container.

var builder = new ContainerBuilder();

// Add your registrations

var container = builder.Build();

// Set the dependency resolver for Web API.
var webApiResolver = new AutofacWebApiDependencyResolver(container);
GlobalConfiguration.Configuration.DependencyResolver = webApiResolver;

// Set the dependency resolver for MVC.
var mvcResolver = new AutofacDependencyResolver(container);
DependencyResolver.SetResolver(mvcResolver);

It is also possible to share registrations between the two because the InstancePerApiRequest and InstancePerHttpRequest lifetime scopes now share the same tag.

GlobalConfiguration.Configuration.DependencyResolver
DependencyResolver.SetResolver

Great answer. The only thing is about "because MVC and Web API can be used independently of one another.". I reckon autofac has two plugins for mvc and webapi separately because the two have different runtime.

GlobalConfiguration
HttpConfiguration
config.DependencyResolver = new AutofacWebApiDependencyResolver(...)

Is it possible to configure Autofac to work with ASP.NET MVC and ASP.N...

asp.net-mvc asp.net-web-api autofac
Rectangle 27 79

It is certainly possible to configure Autofac to work with both MVC and Web API. This is expected to be a very common scenario. There are two separate dependency resolver implementations because MVC and Web API can be used independently of one another. The same applies for the Autofac integrations.

When using both MVC and Web API in the same application each will require its own dependency resolver, though they can be provided with the same instance of the container.

var builder = new ContainerBuilder();

// Add your registrations

var container = builder.Build();

// Set the dependency resolver for Web API.
var webApiResolver = new AutofacWebApiDependencyResolver(container);
GlobalConfiguration.Configuration.DependencyResolver = webApiResolver;

// Set the dependency resolver for MVC.
var mvcResolver = new AutofacDependencyResolver(container);
DependencyResolver.SetResolver(mvcResolver);

It is also possible to share registrations between the two because the InstancePerApiRequest and InstancePerHttpRequest lifetime scopes now share the same tag.

GlobalConfiguration.Configuration.DependencyResolver
DependencyResolver.SetResolver

Great answer. The only thing is about "because MVC and Web API can be used independently of one another.". I reckon autofac has two plugins for mvc and webapi separately because the two have different runtime.

GlobalConfiguration
HttpConfiguration
config.DependencyResolver = new AutofacWebApiDependencyResolver(...)

Is it possible to configure Autofac to work with ASP.NET MVC and ASP.N...

asp.net-mvc asp.net-web-api autofac
Rectangle 27 22

You can register (actually re-register if you are using builder.RegisterControllers()) your controllers with the parameter which will be used during resolve:

builder.RegisterType<SomeController>()
       .WithParameter(ResolvedParameter.ForNamed<IFoo>("bar"));
builder.RegisterType<OtherController>()
       .WithParameter(ResolvedParameter.ForNamed<IFoo>("baz"));

If a controller needs multiple IFoo you can specify the resolve parameter e.g. with name (with a little bit extra syntax, but you can hide it behind an extension method):

builder.RegisterType<ComplexController>().WithParameters(new [] {
 new ResolvedParameter((p,c) => p.Name == "bar",(p,c) => c.ResolveNamed<IFoo>("bar")),
 new ResolvedParameter((p,c) => p.Name == "baz",(p,c) => c.ResolveNamed<IFoo>("baz"))
});

public class ComplexController: Controller
{
    public ComplexController(IFoo baz, IFoo bar)
    {
         //...
    }
}

Thanks, that works. Occasionally a controller will need more than one IFoo - can I specify which parameter name goes to which named implementation?

asp.net mvc - Use named registration in autofac with MVC controller in...

asp.net-mvc autofac
Rectangle 27 4

In Autofac, the innermost scope is always the container. Using the AutofacDependencyResolver, it'd be AutofacDependencyResolver.Current.ApplicationContainer

There is no way from a nested scope (if all you have is an ILifetimeScope) to "walk backward" to get to the container. I'm not necessarily sure you want to do that, anyway.

It sounds like your SingleInstance component is doing some sort of service location, basically, with manual registration/resolution of certain components. If the set of types being registered is fixed, I might recommend (if possible) some redesign of your system, so the SingleInstance component isn't registered as SingleInstance anymore and instead gets registered as InstancePerDependency, then have that take these other items in as constructor parameters.

// Consuming class like this...
public class BigComponent
{
  public void DoSomethingCool()
  {
    using(var scope = ...)
    {
      var c = scope.Resolve<SubComponent>();
      c.DoWork();
    }
  }
}

// ...and container registrations like this...
builder.RegisterType<BigComponent>().SingleInstance();

You might try inverting it a bit:

// Consuming class like this...
public class BigComponent
{
  private SubComponent _c;
  public BigComponent(SubComponent c)
  {
    _c = c;
  }
  public void DoSomethingCool()
  {
    _c.DoWork();
  }
}

// ...and container registrations like this...
builder.RegisterType<BigComponent>().InstancePerDependency();
builder.RegisterType<SubComponent>().InstancePerLifetimeScope();

The idea is to not have to do the on-the-fly registration-and-immediate-resolution thing.

If you're stuck doing service location, you'll need to use AutofacDependencyResolver.Current.ApplicationContainer if you need the absolute innermost scope, but keep in mind any objects you register scoped to InstancePerHttpRequest will not be resolvable if you do that, so you could get into trouble. It really is recommended to use the AutofacDependencyResolver.Current.RequestLifetimeScope instead. That would make your method:

var requestScope = AutofacDependencyResolver.Current.RequestLifetimeScope;
using (var scope = requestScope.BeginLifetimeScope(cb => {
  cb.RegisterType<X>().InstancePerLifetimeScope();
  // ...
}))
{
    var comp = scope.Resolve<X>();
    // ...
}

In a testing environment, the AutofacDependencyResolver lets you swap in the provider that dictates how request lifetimes get generated. You can implement a simple/stub one like this:

public class TestLifetimeScopeProvider : ILifetimeScopeProvider
{
    readonly ILifetimeScope _container;
    private ILifetimeScope _lifetimeScope = null;

    public TestLifetimeScopeProvider(ILifetimeScope container)
    {
        if (container == null) throw new ArgumentNullException("container");
        _container = container;
    }

    public ILifetimeScope ApplicationContainer
    {
        get { return _container; }
    }

    public ILifetimeScope GetLifetimeScope()
    {
        if (_lifetimeScope == null)
        {
            _lifetimeScope = ApplicationContainer.BeginLifetimeScope("httpRequest")
        }
        return _lifetimeScope;
    }

    public void EndLifetimeScope()
    {
        if (_lifetimeScope != null)
            _lifetimeScope.Dispose();
    }
}

Again, just a stub for unit testing, not something you'd ever use in production.

Then when you wire up the DependencyResolver in your test, you provide your lifetime scope provider:

var lsProvider = new TestLifetimeScopeProvider(container);
var resolver = new AutofacDependencyResolver(container, lsProvider);
DependencyResolver.SetResolver(resolver);

This lets you use InstancePerHttpRequest and such inside unit tests without actually having a real request context. It also means you should be able to use the request lifetime scope in your registration/resolution method and not have to fall back on the application container.

The "BigComponent" in my case is a registry that holds certain objects for the whole life of the application. The nested scope is used during application startup (first HTTP request) to instantiate some types discovered dynamically (plugin architecture). My current solution is to inject a Func<ILifetimeScope> into the "BigComponent" that is currently registered as ()=>AutofacDependencyResolver.Current.RequestLifetimeScope. Still not great, but it leaves the static reference to the service locator out of the scope. [continued]

BTW: with innermost scope I meant the most deeply nested scope. For me, the application container is the outermost scope.

My misunderstanding on reference to innermost/outermost, sorry. Either way, you can't really walk the stack in either direction, so if you have to do the service location, you're stuck with AutofacDependencyResolver. Note if you use MVC IDependencyResolver, then DependencyResolver.Current.GetService will always come out of the request lifetime, so you may not need that lambda... oh, except you're registering on the fly. So, yep, you'll still need that.

Generally speaking, I try to invert this stuff. If I have some application-level thing with cached objects, I'll take those objects as parameters into my plugins rather than vice-versa. Intentional design to avoid the service location, if you will. Sometimes it's unavoidable, but I can't help but think there's a "code smell" here you could address with a little refactoring.

Problably my example wasn't that great. What I try to achieve all happens during initialization to set up the container. I don't know the types of the components to register until runtime, so I can't resolve them statically. Instead, I register them dynamically and resolve them directly so that their dependencies are nicely resolved without explicit service location. I'll be back on sunday with a better description of what I'm trying to do. Thanks so far already for your time. Probably it'll boil down to my Func<ILifetimeScope> approach, as I can't seem to get the innermost scope otherwise.

asp.net mvc - Autofac: any way to resolve the innermost scope? - Stack...

asp.net-mvc asp.net-mvc-3 ninject autofac
Rectangle 27 1

MEF will not help you solve extensibility issues in the case you have described in the question, because it doesn't seem to have any. What MEF can bring to the table for this particular case is Dependency Injection. If you develop your application in a way that the presentation layer depends on business abstraction and the business layer depends on a data access abstraction rather than on concrete implementation, you will get a highly decoupled application that is easy to test, maintain and change without affecting unnecessary components. Here is one way to do this:

Lets say you have data access class that performs CRUD operations on employees:

[Export(typeof(IEmployeeRepository))]
public class EmployeeRepository : IEmployeeRepository
{
    //Some logic here
}

As you can see the EmployeeRepository class implements IEmployeeRepository interface which adds the level of abstraction that is needed to develop a decoupled application. Now lets say that in the business layer you have a class that needs to call some method from the EmployeeRepository class. To be able to call a method of EmployeeRepository, you would need an instance of it. Without using MEF (or any other IoC framework, this would be a way to do it:

public class EmployeeManager
{
    private EmployeeRepository _employeeRepository;

    public EmployeeManager
    {
        _employeeRepository = new EmployeeRepository();
    } 
}

By using the above code sample, a hard dependency between the EmployeeManager and EmployeeRepository classes is created. This hard dependency is difficult to isolate when writing unit tests and causes any change of the EmployeeRepository class to directly affect the EmployeeManager class. By refactoring the code sample a little bit and putting MEF into the game, you'll get this:

[Export(typeof(IEmployeeManager))]
public class EmployeeManager : IEmployeeManager
{
    private IEmployeeRepository _employeeRepository;

    [ImportingConstructor]
    public EmployeeManager(IEmployeeRepository employeeRepository)
    {
        _employeeRepository = employeeRepository;
    } 
}

As you can see the EmployeeManager class now doesn't depend on the EmployeeRepository class, but it depends on IEmployeeRepository interface, in other words it depends on abstraction. And it doesn't create the instance of EmployeeRepository class by itself. That job is left to MEF. By now it should be clear that export and ImportingConstructor attributes are part of MEF and are used by it to discover parts and resolve dependencies at runtime. With the last code sample the classes are decoupled, easy to test and maintain and you can change the internal logic in EmployeeRepository class without making EmployeeManager class aware of it. Of course the contract between them, IEmployeeRepository have to be maintained.

The above said, can be used to decouple the presentation layer from the business layer also. Also the above said, can be implemented by using any other IoC framework, like Ninject, Autofac, StructureMap etc. The difference between these IoC frameworks and MEF is that if you use them, you'll need to configure at application start which instance gets created when some interface is encountered:

//something like this, in the case of Ninject
this.Bind<IEmployeeRepository>().To<EmployeeRepository>();

On the other hand, MEF has the ability to discover parts at runtime. On application start, you'll just need to inform it where to look for parts: Directory, Assembly, Type etc. The auto-wire capabilities of MEF (the ability to discover parts at runtime), make it more than a regular IoC framework. This ability makes MEF great for developing pluggable and extensible applications because you'll be able to add plugins while the application is running. MEF is able load them and let the application to use them.

Well, not really blocks... If you inspect the grey elements in your answer (the ones wrapped in ` (backticks)), you'll see that they're <code> tags. MEF, Dependency Injection, IoC, Export, Ninject, Autofac, StructureMap, Directory, Assembly and Type is not code

You are right. I've been using backticks for highlighting, but it should be used for inline code.

Yes. If you absolutely have to highlight something. Use bold :)

asp.net mvc - Using MEF , what would be the Extensible points in a web...

asp.net-mvc design-patterns mef
Rectangle 27 7

Here is simple Integration test sample for your ASP.NET Web API application. This doesn't mainly test your routes but it invisibly tests them. Also, I am using XUnit, Autofac and Moq here.

[Fact, NullCurrentPrincipal]
public async Task 
    Returns_200_And_Role_With_Key() {

    // Arrange
    Guid key1 = Guid.NewGuid(),
         key2 = Guid.NewGuid(),
         key3 = Guid.NewGuid(),
         key4 = Guid.NewGuid();

    var mockMemSrv = ServicesMockHelper
        .GetInitialMembershipService();

    mockMemSrv.Setup(ms => ms.GetRole(
            It.Is<Guid>(k =>
                k == key1 || k == key2 || 
                k == key3 || k == key4
            )
        )
    ).Returns<Guid>(key => new Role { 
        Key = key, Name = "FooBar"
    });

    var config = IntegrationTestHelper
        .GetInitialIntegrationTestConfig(GetInitialServices(mockMemSrv.Object));

    using (var httpServer = new HttpServer(config))
    using (var client = httpServer.ToHttpClient()) {

        var request = HttpRequestMessageHelper
            .ConstructRequest(
                httpMethod: HttpMethod.Get,
                uri: string.Format(
                    "https://localhost/{0}/{1}", 
                    "api/roles", 
                    key2.ToString()),
                mediaType: "application/json",
                username: Constants.ValidAdminUserName,
                password: Constants.ValidAdminPassword);

        // Act
        var response = await client.SendAsync(request);
        var role = await response.Content.ReadAsAsync<RoleDto>();

        // Assert
        Assert.Equal(key2, role.Key);
        Assert.Equal("FooBar", role.Name);
    }
}

There are a few external helpers I use for this test. The one of them is the NullCurrentPrincipalAttribute. As your test will run under your Windows Identity, the Thread.CurrentPrincipal will be set with this identity. So, if you are using some sort of authorization in your application, it is best to get rid of this in the first place:

public class NullCurrentPrincipalAttribute : BeforeAfterTestAttribute {

    public override void Before(MethodInfo methodUnderTest) {

        Thread.CurrentPrincipal = null;
    }
}
MembershipService

The GetInitialServices creates the Autofac container for me.

private static IContainer GetInitialServices(
    IMembershipService memSrv) {

    var builder = IntegrationTestHelper
        .GetEmptyContainerBuilder();

    builder.Register(c => memSrv)
        .As<IMembershipService>()
        .InstancePerApiRequest();

    return builder.Build();
}
GetInitialIntegrationTestConfig
internal static class IntegrationTestHelper {

    internal static HttpConfiguration GetInitialIntegrationTestConfig() {

        var config = new HttpConfiguration();
        RouteConfig.RegisterRoutes(config.Routes);
        WebAPIConfig.Configure(config);

        return config;
    }

    internal static HttpConfiguration GetInitialIntegrationTestConfig(IContainer container) {

        var config = GetInitialIntegrationTestConfig();
        AutofacWebAPI.Initialize(config, container);

        return config;
    }
}

The RouteConfig.RegisterRoutes method basically registers my routes. I also have a little extension method to create an HttpClient over the HttpServer.

internal static class HttpServerExtensions {

    internal static HttpClient ToHttpClient(
        this HttpServer httpServer) {

        return new HttpClient(httpServer);
    }
}

Finally, I have a static class called HttpRequestMessageHelper which has bunch of static methods to construct a new HttpRequestMessage instance.

internal static class HttpRequestMessageHelper {

    internal static HttpRequestMessage ConstructRequest(
        HttpMethod httpMethod, string uri) {

        return new HttpRequestMessage(httpMethod, uri);
    }

    internal static HttpRequestMessage ConstructRequest(
        HttpMethod httpMethod, string uri, string mediaType) {

        return ConstructRequest(
            httpMethod, 
            uri, 
            new MediaTypeWithQualityHeaderValue(mediaType));
    }

    internal static HttpRequestMessage ConstructRequest(
        HttpMethod httpMethod, string uri,
        IEnumerable<string> mediaTypes) {

        return ConstructRequest(
            httpMethod,
            uri,
            mediaTypes.ToMediaTypeWithQualityHeaderValues());
    }

    internal static HttpRequestMessage ConstructRequest(
        HttpMethod httpMethod, string uri, string mediaType, 
        string username, string password) {

        return ConstructRequest(
            httpMethod, uri, new[] { mediaType }, username, password);
    }

    internal static HttpRequestMessage ConstructRequest(
        HttpMethod httpMethod, string uri, 
        IEnumerable<string> mediaTypes,
        string username, string password) {

        var request = ConstructRequest(httpMethod, uri, mediaTypes);
        request.Headers.Authorization = new AuthenticationHeaderValue(
            "Basic",
            EncodeToBase64(
                string.Format("{0}:{1}", username, password)));

        return request;
    }

    // Private helpers
    private static HttpRequestMessage ConstructRequest(
        HttpMethod httpMethod, string uri,
        MediaTypeWithQualityHeaderValue mediaType) {

        return ConstructRequest(
            httpMethod, 
            uri, 
            new[] { mediaType });
    }

    private static HttpRequestMessage ConstructRequest(
        HttpMethod httpMethod, string uri,
        IEnumerable<MediaTypeWithQualityHeaderValue> mediaTypes) {

        var request = ConstructRequest(httpMethod, uri);
        request.Headers.Accept.AddTo(mediaTypes);

        return request;
    }

    private static string EncodeToBase64(string value) {

        byte[] toEncodeAsBytes = Encoding.UTF8.GetBytes(value);
        return Convert.ToBase64String(toEncodeAsBytes);
    }
}

I am using Basic Authentication in my application. So, this class has some methods which construct an HttpRequestMessege with the Authentication header.

At the end, I do my Act and Assert to verify the things I need. This may be an overkill sample but I think this will give you a great idea.

Informative answer, but why is this better than unit testing your routes?

c# - How can you unit test ASP.NET Web API routing? - Stack Overflow

c# unit-testing asp.net-web-api
Rectangle 27 0

We're doing something very similar in a project, which I have got working using Autofac. I have my UserManager injected into UserService (just a domain layer class at the present time rather than an actual service), but can successfully access the UserManager from both Api and MVC controller methods. Here's how I've set things up, which may help. I haven't created separate modules for API and MVC stuff, just thrown it all in together (your resolvers are set up correctly by the way).

public class WebModule : Module
{
    protected override void Load(ContainerBuilder builder)
    {
        builder.RegisterFilterProvider();
        builder.RegisterType<ExtensibleActionInvoker>().As<IActionInvoker>();
        builder.RegisterControllers(Assembly.GetExecutingAssembly())
          .InjectActionInvoker();
        builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

        // OWIN
        builder.Register(c => HttpContext.Current.GetOwinContext())
          .As<IOwinContext>().InstancePerLifetimeScope();

        // Module chaining
        builder.RegisterModule<DataModule>();
    }
}

Next, the Data Module (there's other modules too but they aren't relevant):

public class DataModule : Module
{
    protected override void Load(ContainerBuilder builder)
    {
        var context = new EntityContext();
        builder.RegisterInstance(context).As<IEntityContext>().SingleInstance();
        builder.Register(x => new UserStore<ApplicationUser>(context))
          .As<IUserStore<ApplicationUser>>().InstancePerLifetimeScope();
        builder.Register(x =>
        {
            var userStore = x.Resolve<IUserStore<ApplicationUser>>();
            var userManager = new UserManager<ApplicationUser>(userStore);
            return userManager;
        });
    }
}

My EntityContext is an IdentityDbContext<ApplicationUser> that I've also wrapped in an interface so I can set up a fake user store and stuff like that.

The only thing that I can see that's different about what you're doing is that you don't seem to be passing the IdentityContext into your UserManager when it's registered.

thanks levelnis. I'll take a look. I'm assuming you started off with an MVC application. Did you have to do anything special in the Startup class re: Owin when you were integrating web-api authentication?

Maybe that's the difference - all of the authentication on our site is done through MVC - there's no Web API-specific authentication going on

so, you mean all api actions are public? Or that you authenticate via MVC and only authenticated users can use the api?

The latter - authentication happens via MVC and only authenticated users can use the API

"No owin.Environment item was found in the context" exception in ASP.N...

asp.net-mvc asp.net-web-api visual-studio-2013 owin
Rectangle 27 0

You will have to compose your container on the application level, e.g. using an OwinStartup class or similar. That said, I usually separate out the dependency setup for each assembly/project into their own Autofac module. This way, the assemblies become more self-contained. The application level setup also becomes much cleaner, its only responsibility is pulling in the various modules and building the container.

asp.net mvc - MVC Dependency Injection Autofac, where to specify depen...

asp.net-mvc dependency-injection autofac
Rectangle 27 0

We're doing something very similar in a project, which I have got working using Autofac. I have my UserManager injected into UserService (just a domain layer class at the present time rather than an actual service), but can successfully access the UserManager from both Api and MVC controller methods. Here's how I've set things up, which may help. I haven't created separate modules for API and MVC stuff, just thrown it all in together (your resolvers are set up correctly by the way).

public class WebModule : Module
{
    protected override void Load(ContainerBuilder builder)
    {
        builder.RegisterFilterProvider();
        builder.RegisterType<ExtensibleActionInvoker>().As<IActionInvoker>();
        builder.RegisterControllers(Assembly.GetExecutingAssembly())
          .InjectActionInvoker();
        builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

        // OWIN
        builder.Register(c => HttpContext.Current.GetOwinContext())
          .As<IOwinContext>().InstancePerLifetimeScope();

        // Module chaining
        builder.RegisterModule<DataModule>();
    }
}

Next, the Data Module (there's other modules too but they aren't relevant):

public class DataModule : Module
{
    protected override void Load(ContainerBuilder builder)
    {
        var context = new EntityContext();
        builder.RegisterInstance(context).As<IEntityContext>().SingleInstance();
        builder.Register(x => new UserStore<ApplicationUser>(context))
          .As<IUserStore<ApplicationUser>>().InstancePerLifetimeScope();
        builder.Register(x =>
        {
            var userStore = x.Resolve<IUserStore<ApplicationUser>>();
            var userManager = new UserManager<ApplicationUser>(userStore);
            return userManager;
        });
    }
}

My EntityContext is an IdentityDbContext<ApplicationUser> that I've also wrapped in an interface so I can set up a fake user store and stuff like that.

The only thing that I can see that's different about what you're doing is that you don't seem to be passing the IdentityContext into your UserManager when it's registered.

thanks levelnis. I'll take a look. I'm assuming you started off with an MVC application. Did you have to do anything special in the Startup class re: Owin when you were integrating web-api authentication?

Maybe that's the difference - all of the authentication on our site is done through MVC - there's no Web API-specific authentication going on

so, you mean all api actions are public? Or that you authenticate via MVC and only authenticated users can use the api?

The latter - authentication happens via MVC and only authenticated users can use the API

"No owin.Environment item was found in the context" exception in ASP.N...

asp.net-mvc asp.net-web-api visual-studio-2013 owin
Rectangle 27 0

You will have to compose your container on the application level, e.g. using an OwinStartup class or similar. That said, I usually separate out the dependency setup for each assembly/project into their own Autofac module. This way, the assemblies become more self-contained. The application level setup also becomes much cleaner, its only responsibility is pulling in the various modules and building the container.

asp.net mvc - MVC Dependency Injection Autofac, where to specify depen...

asp.net-mvc dependency-injection autofac