Coder Social home page Coder Social logo

autofac.mvc's Introduction

Autofac character Autofac logo

Autofac is an IoC container for Microsoft .NET. It manages the dependencies between classes so that applications stay easy to change as they grow in size and complexity. This is achieved by treating regular .NET classes as components.

Build status codecov NuGet

Autofac on Stack Overflow Join the chat at https://gitter.im/autofac/autofac

Get Packages

You can get Autofac by grabbing the latest NuGet package. There are several application integration and extended functionality packages to choose from. If you're feeling adventurous, continuous integration builds are on MyGet.

Release notes are available on GitHub.

Get Help

Need help with Autofac? We have a documentation site as well as API documentation. We're ready to answer your questions on Stack Overflow or check out the discussion forum.

Get Started

Our Getting Started tutorial walks you through integrating Autofac with a simple application and gives you some starting points for learning more.

Super-duper quick start:

Register components with a ContainerBuilder and then build the component container.

var builder = new ContainerBuilder();

builder.Register(c => new TaskController(c.Resolve<ITaskRepository>()));
builder.RegisterType<TaskController>();
builder.RegisterInstance(new TaskController());
builder.RegisterAssemblyTypes(controllerAssembly);

var container = builder.Build();

Resolve services from a lifetime scope - either the container or a nested scope:

var taskController = container.Resolve<TaskController>();

There is a growing number of application integration libraries that make using Autofac with your application a snap. Support for several popular frameworks is also available through the "Extras" packages.

Intrigued? Check out our Getting Started walkthrough!

Project

Autofac is licensed under the MIT license, so you can comfortably use it in commercial applications (we still love contributions though).

File issues in the repo with the associated feature/code.

Sponsors

Autofac is supported by AWS. Thanks for your contribution!

Contributing / Pull Requests

Refer to the Contributor Guide for setting up and building Autofac source.

You can also open this repository right now in VS Code.

autofac.mvc's People

Contributors

alexmg avatar alistairjevans avatar alsami avatar amro9 avatar craigfowler avatar pengweiqhca avatar shiftkey avatar tillig avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

autofac.mvc's Issues

Register mvc controllers with autofac 4 beta fails

Hi,

I'm currently working on an application that use autofac xml/json integration in its latest form. However If I try and inject into MVC Controllers (using the latest Autofac.Integration.Mvc and the normal registration process for Mvc controllers as defined in the documentation) it doesn't work. Actually, it throws this exception:

Attempt by security transparent method 'Autofac.Integration.Mvc.RequestLifetimeScopeProvider..ctor(Autofac.ILifetimeScope)' to access security critical type 'Autofac.ILifetimeScope' failed.

Assembly 'Autofac.Integration.Mvc, Version=3.3.0.0, Culture=neutral, PublicKeyToken=17863af14b0044da' is marked with the AllowPartiallyTrustedCallersAttribute, and uses the level 2 security transparency model. Level 2 transparency causes all methods in AllowPartiallyTrustedCallers assemblies to become security transparent by default, which may be the cause of this exception.

I also use api controllers injection and that works fine.

Is it occurring because of versioning issues? Or perhaps there might be another issue?

I'm currently using VS2013 .NET 4.5. It worth to mention that the mvc controllers are located in a different assembly than the one i'm using to configure autofac. Furthermore, each assembly has it's own autofac's module to register specific component such as controllers.

Could not load file or assembly 'System.Web.Mvc, Version=5.1.0.0

I recently updated my System.Web.Mvc to 5.2.3.0 and now the MVC 5 library is throwing the following error:

Could not load file or assembly 'System.Web.Mvc, Version=5.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

If I uncomment the autofac stuff it sorta works (it gripes about missing autofac but figured that'd happen)

Update AutofacFilterProvider.GetFilters() to skip evaluation if the controller instance is null

When the controllerContext.Controller property is null, the call to GetType() to populate the filterContext throws an exception.

We've never seen this exception before, and are only now seeing it with a configuration change. Given that fact, I would normally assume that this is a problem with our configuration (I can't figure out how/why the Controller property would be null).

HOWEVER, AutofacFilterProvider inherits from System.Web.Mvc.FilterAttributeFilterProvider, and that base implementation of GetFilters() does a null check on the Controller property. Therefore, I assume there must be a normal condition under which that property is expected to be null. If so, then I expect that the null check should also be done in this method.

Integration not compatible with Autofac 5.0 Release Candidate

The Autofac.Mvc integration has build errors when built against the latest Autofac Release candidate in MyGet, specifically:

src\Autofac.Integration.Mvc\RegistrationExtensions.cs(457,44,457,60): error CS1501: No overload for method 'ResolveComponent' takes 2 arguments

The IComponentContext.ResolveComponent method has changed signature, which breaks one specific bit of code.

In addition, I believe the NuSpec will need updating to change the version constraints from [3.5.0,5.0.0) to [5.0.0, 6.0.0), because this version will no longer be compatible with older Autofac versions.

Add factory/accessor function for AutofacDependencyResolver.Current

It doesn't seem we can win on the way we get AutofacDependencyResolver.Current - whether it's registered in a lifetime scope or unwound from the currently set resolver.

By default, the current behavior is great, but for folks who still need to do some sort of unsupported decoration, we should offer a way to override the default behavior. A sort of factory method/function that is used to retrieve the resolver could help.

public void SetCurrentResolverAccessor(Func<AutofacDependencyResolver> accessor)

Set it to null to return to the default behavior; otherwise set it to something specific to take control of how to get the current Autofac dependency resolver.

Registering open generics not working with ASP.NET Core 1.

I have Autofac setup for my asp.net core project and is working fine except when I try to resolve generic types which I have registered in as

builder.RegisterGeneric(typeof(Repository<>)).As(typeof(IRepository<>));

When I try to resolve the type in any of my Controllers using

public HomeController (Repository<User> userRepository) { _userRepository = userRepository; }

I get the following error

`System.InvalidOperationException: Unable to resolve service for type 'ResumeMaker.DbPortal.Repository`1[ResumeMaker.Data.Models.Core.User]' while attempting to activate 'ResumeMaker.Controllers.HomeController'.
   at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired)
   at lambda_method(Closure , IServiceProvider , Object[] )
   at Microsoft.AspNet.Mvc.Infrastructure.DefaultTypeActivatorCache.CreateInstance[TInstance](IServiceProvider serviceProvider, Type implementationType)
   at Microsoft.AspNet.Mvc.Controllers.DefaultControllerActivator.Create(ActionContext actionContext, Type controllerType)
   at Microsoft.AspNet.Mvc.Controllers.DefaultControllerFactory.CreateController(ActionContext actionContext)
   at Microsoft.AspNet.Mvc.Controllers.ControllerActionInvoker.CreateInstance()
   at Microsoft.AspNet.Mvc.Controllers.FilterActionInvoker.<InvokeAllActionFiltersAsync>d__52.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at Microsoft.AspNet.Mvc.Controllers.FilterActionInvoker.<InvokeExceptionFilterAsync>d__51.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNet.Mvc.Controllers.FilterActionInvoker.<InvokeAsync>d__44.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at Microsoft.AspNet.Mvc.Infrastructure.MvcRouteHandler.<RouteAsync>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at Microsoft.AspNet.Routing.Template.TemplateRoute.<RouteAsync>d__27.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at Microsoft.AspNet.Routing.RouteCollection.<RouteAsync>d__9.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at Microsoft.AspNet.Builder.RouterMiddleware.<Invoke>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at Microsoft.AspNet.Authentication.AuthenticationMiddleware`1.<Invoke>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNet.Authentication.AuthenticationMiddleware`1.<Invoke>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at Microsoft.AspNet.Authentication.AuthenticationMiddleware`1.<Invoke>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNet.Authentication.AuthenticationMiddleware`1.<Invoke>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at Microsoft.AspNet.IISPlatformHandler.IISPlatformHandlerMiddleware.<Invoke>d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at Microsoft.AspNet.Diagnostics.DeveloperExceptionPageMiddleware.<Invoke>d__7.MoveNext()`

Am I missing anything here?

Thanks

Request disposed in authentication middleware

I'm trying to resolve a registered service in my CookieAuthenticationProvider but it complains about the scope already being disposed. Seems like this shouldn't be disposed yet or there should be a way to retrieve the service without registering it as a singleton.

Error: Instances cannot be resolved and nested lifetimes cannot be created from this LifetimeScope as it has already been disposed.

...
Provider = new CookieAuthenticationProvider
{
    OnResponseSignedIn = async (CookieResponseSignedInContext context) =>
    {
        IProfileService profileService = AutofacDependencyResolver.Current.GetService<IProfileService>();
...

Autofac ASP.NET MVC 5 Integration cannot install

Hey,
I can not install Autofac ASP.NET MVC 5 Integration successful on my pc,
my local environment is:
VS Pro 2013, Update 5
MVC project is .net framework 4.5, MVC 5.2.3.
I was installed AutoFac first, and then trying to install Autofac ASP.NET MVC 5 Integration, but failed.
Error message is chinese, i'm trying to translate it as below:
You are trying to install this package to a will ". Netframework, version = 4.5 "as the target of the project, But this package does not contain any compatible with the framework of the assembly references or content files.

Different resolving from constructor injection and DependencyResolver.Current.GetService

Hello evryone. I have a question about this two types of resolving.
(Autofac 4.4.0 // Autofac.Mvc5 4.0.1 // Autofac.WebApi2 // 4.0.1)
I have interface

public interface IUserContext
{
	User User { get; set; }
}

I register it with ContainerBuilder:

var builder = new ContainerBuilder();
builder.RegisterControllers(typeof(BaseController).Assembly);
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
builder.RegisterType<UserContext>().As<IUserContext>().InstancePerRequest();
builder.RegisterType<TaxAuditLogicToTableViewModelConverter>().AsSelf().InstancePerRequest();
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);

So, i have authorization attribute. In attribute i resolve another service(DependencyResolver.Current.GetService<IAuthorization>()), in implementation of IAuthorization, IUserContext pass as contructor parameter and set User field.
I'll try get IUserContext two ways:

class FinalStepLogicToViewConverter : ITypeConverter<TaxAudit, LastStepViewModel>
{
	public FinalStepLogicToViewConverter(IUserContext uc)
	{
		var nullReference = uc.User;//thats null
		var notNullReference = DependencyResolver.Current.GetService<IUserContext>().User;//thats not null
	}
}
//FinalStepLogicToViewConverter need me for using in automapper:
...
CreateMap<X, Y>().ConvertUsing<FinalStepLogicToViewConverter>();
...

Why in one case it's null, and not null in another? How can i solve this without direct call dependecy resolver?

Add .NET Framework 4.5 support to packaging

I tested locally and repackaged. Seems to work just fine. I can post a PR for the nuspec if you prefer.

May need to rinse and repeat for Autofac.Mvc.Owin or other packages along similar lines.

Thank you...

properties Auto wiring does not work with asp.net 5

From @devmondo on June 27, 2015 0:20

hi,
i have a base controller and i dont want to use constructor injection so i tried below but it does not resolve the property, and yes i have IAsyncDocumentSession registered with Autofac and it works using constructor injection

builder.Register(c => new BaseController()).OnActivated(e =>
{
    e.Instance.dbSession= e.Context.Resolve<IAsyncDocumentSession>();
});

or this


builder.RegisterType<BaseController>()
       .PropertiesAutowired();

thanks in advanced.

Copied from original issue: autofac/Autofac#653

System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection

We noticed a race condition with the method builder.RegisterFilterProvider() which is not thread-safe. We had multiple modules - some inherited that were also calling this method. Since this method is removing from a shared dictionary System.Web.Mvc.FilterProviders.Providers - it should lock access to prevent the race condition in cases where the filter has already been removed from the shared dictionary.

Race Condition - FilterProviders.Providers

image

Simple Reproduction - Overstated

var builder = new ContainerBuilder();
Parallel.For(1, 10, c => builder.RegisterFilterProvider());

This above code will generate the following exception:

System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
   at System.ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource)
   at System.Collections.Generic.List`1.RemoveAt(Int32 index)
   at System.Web.Mvc.FilterProviderCollection.RemoveItem(Int32 index)
   at System.Collections.ObjectModel.Collection`1.Remove(T item)
   at Autofac.Integration.Mvc.RegistrationExtensions.RegisterFilterProvider(ContainerBuilder builder)

Note: his bug has taken us months to identify and narrow down to this single line - hopefully we can squash this for others benefit.

Allow ModelBinding resolution to work with subclasses

From @mmiller678 on December 3, 2014 18:25

I can't get the Autofac model binding for MVC to work with subclasses - which I think is the intended behavior. The current Autofac model bind provider matches on exact type like the built in MVC one does.

Ideally it would be nice if the model binder could be registered to say I want to be used with the any subclasses that implement the specified type - i.e.

Ideally I would like to do something like this:

builder.RegisterType()
.AsModelBinderForTypesAndSubclasses(typeof(IEntity))
.PropertiesAutowired();
builder.RegisterModelBinderProvider();

autofacModelBinderProvider.GetBinder(typeof(EntityImplementation)) would return EntityModelBinder

Is there a way to do this in the current implementation? My current solution is to create my own provider and resolve the binders thru the dependency resolver, but I would prefer to use a purely Autofac solution if possible.

Copied from original issue: autofac/Autofac#603

Registering one filter type for multiple controllers doesn't work in one statement

The issue was also in WebpApi but it is resolved. The fix is needed in Mvc as well. The following line of code doesn't work -

        builder.Register(
                ctx => c.Resolve<IProperty>())
            .AsActionFilterFor<BaseController1>()
            .AsActionFilterFor<BaseController2>()
            .InstancePerRequest();

Error: System.ArgumentException: 'An item with the same key has already been added.'

Part of Stacktrace:

   at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
   at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
   at System.Collections.Generic.Dictionary`2.Add(TKey key, TValue value)
   at Autofac.Builder.RegistrationBuilder`3.WithMetadata(String key, Object value)
   at Autofac.Integration.Mvc.RegistrationExtensions.AsFilterFor[TFilter,TController](IRegistrationBuilder`3 registration, String metadataKey, Int32 order)
   at Autofac.Integration.Mvc.RegistrationExtensions.AsActionFilterFor[TController](IRegistrationBuilder`3 registration, Int32 order)

Incorrect Grammar in "src/Autofac.Integration.Mvc/AutofacDependencyResolver.cs" Constructor Comment

Issue description

The comment of the constructor AutofacDependencyResolver.cs has a grammatical error.
It was probably copy pasted before each constructor:

image

The phrase "The container that nested lifetime scopes will be create from" contains an incorrect verb tense

Desired Solution

Suggested Correction: "The container from which nested lifetime scopes will be created"

Additional Info

There are no expected behavior changes, only a comment improvement.

Get a can not load assembly "System.Web.Mvc, Version=5.1.0.0" error when i put project in a directory name contain "#"

I'm using Autofac.Mvc 4.0.0.0 and my ASP.NET MVC version is 5.2.3.0. I create a project on desktop, using Autofac it's work. when i copy this project to my project folder(which contain "#") it's get this error.
First I thought this a config/nuget version/framework version/refrence problem. Then i try them all, still get this error. And the project build success but this error appear when the project run.
Finally i found out this error only appear when i put the project in to the specific folder which name contain "#", then i realize it's maybe a Autofac bug. And why i get a error like this, it's nothing relate to a directory issue. Guess it just load 5.1.0.0 version when it try load assembly error.

Using AutofacServiceLocator on type with InstancePerRequest() causes error

I get "No scope with a tag matching 'AutofacWebRequest' is visible from the scope in which the instance was requested" when trying to get object using service locator.
P.S: no need for comments that do not use service locator. anti-pattern. this code is just for demo purposes.

public static class IocConfig
    {
        public static void Register()
        {
            var container = ConfigureContainer();

            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

            var serviceLocator = new AutofacServiceLocator(container);
            ServiceLocator.SetLocatorProvider(() => serviceLocator);
        }

        private static IContainer ConfigureContainer()
        {
            var builder = new ContainerBuilder();

            ConfigureMvc(builder);
            ConfigureModules(builder);

            return builder.Build();
        }

        private static void ConfigureModules(ContainerBuilder builder)
        {
            builder.RegisterModule<ServiceModule>();
            builder.RegisterModule<AutofacWebTypesModule>();
        }

        private static void ConfigureMvc(ContainerBuilder builder)
        {
            builder.RegisterControllers(typeof(WebApiApplication).Assembly);
            builder.RegisterModelBinders(typeof(WebApiApplication).Assembly);
            builder.RegisterModelBinderProvider();
            builder.RegisterFilterProvider();
        }
    }

    public class ServiceModule : Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterType<UserService>().As<IUserService>().InstancePerRequest();
        }
    }

   public interface IUserService
    {
        void DoSomething();
    }

    public class UserService : IUserService
    {
        public void DoSomething()
        {
        }
    }

 public class HomeController : Controller
    {
        private readonly IUserService _userService;

        public HomeController(IUserService userService)
        {
            _userService = userService;
        }

        public ActionResult Index()
        {
            var userService2 = ServiceLocator.Current.GetInstance<IUserService>(); //error is thrown here
            userService2.DoSomething();

            ViewBag.Title = "Home Page";

            return View();
        }
    }

RequestLifetimeScopeProvider.EndLifetimeScope throws NullReferenceException when both OWIN middleware and MVC integration

Using the Autofac MVC integration coexisting with the OWIN integration in the same application can result in an exception raised from the MVC integration's RequestLifetimeScopeProvider class.

Reproduction

This can occur when an HTTP request uses only the OWIN middleware and does not make any use of the regular MVC5 stack. I experienced this when making use of OAuth functionality from OWIN.

I have only tried this with ASP.NET MVC5 and not the newer ASP.NET Core.

In my first reproduction case I was using an application which used both OWIN middleware (OAuth JWT bearer token auth in my case) which included some injected components and also ASP.NET MVC5 in the same app. I received the following exception when performing an HTTP request to the oauth JWT token endpoint:

[System.NullReferenceException]: Object reference not set to an instance of an object
  at Autofac.Integration.Mvc.RequestLifetimeScopeProvider.get_LifetimeScope () [0x00005] in <12b7e1f0a3c84261a70bb084357848f1>:0 
  at Autofac.Integration.Mvc.RequestLifetimeScopeProvider.EndLifetimeScope () [0x00000] in <12b7e1f0a3c84261a70bb084357848f1>:0 
  at Autofac.Integration.Mvc.RequestLifetimeHttpModule.OnEndRequest (System.Object sender, System.EventArgs e) [0x0000c] in <12b7e1f0a3c84261a70bb084357848f1>:0 
  at (wrapper delegate-invoke) <Module>:invoke_void_object_EventArgs (object,System.EventArgs)
  at System.Web.HttpApplication.PipelineDone () [0x0001c] in <e6ac3c4d7fe1491da2402c546c0c1c72>:0 

Root cause

Because the MVC stack is not used, HttpContext.Current is null. However, RequestLifetimeHttpModule triggers RequestLifetimeScopeProvider.EndLifetimeScope regardless as it's registered as an HTTP module. The lifetime scope provider has a hard dependency upon HttpContext.Current and crashes with an exception in this case.

Workaround

You may work around this by subclassing RequestLifetimeScopeProvider as follows.

public class OwinCompatibleLifetimeScopeProvider : RequestLifetimeScopeProvider, ILifetimeScopeProvider
{
  public new void EndLifetimeScope()
  {
    // No-op if HttpContext.Current is null
    if(HttpContext.Current != null)
    {
      base.EndLifetimeScope();
    }
  }

  void ILifetimeScopeProvider.EndLifetimeScope()
  {
    this.EndLifetimeScope();
  }

  public OwinCompatibleLifetimeScopeProvider(ILifetimeScope scope) : base(scope) {}
}

Then, when configuring Autofac for MVC, construct and use the alternative provider explicitly:

var container = GetContainer();
var provider = new OwinCompatibleLifetimeScopeProvider(container);
DependencyResolver.SetResolver(new AutofacDependencyResolver(container, provider));

The presence of concurrency issues

concurrency to new more instances of RequestLifetimeScopeProvider

that will case Some concurrent object will not be released in "concurrent RequestLifetimeScopeProvider "lifetimescope ??

AutofacDependencyResolver.cs
222

Exception when requesting the first view

Hi,

In the past few days I've migrated an existing MVC5+Owin+SignalR (latest) web application to use latest Autofac and the integration libraries.

After solving the first few issues, I get the following exception which I'm unable to sort out.

Autofac.Core.DependencyResolutionException: None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'System.Web.Mvc.AjaxHelper`1[System.Object]' can be invoked with the available services and parameters:
Cannot resolve parameter 'System.Web.Mvc.IViewDataContainer viewDataContainer' of constructor 'Void .ctor(System.Web.Mvc.ViewContext, System.Web.Mvc.IViewDataContainer)'.
Cannot resolve parameter 'System.Web.Mvc.IViewDataContainer viewDataContainer' of constructor 'Void .ctor(System.Web.Mvc.ViewContext, System.Web.Mvc.IViewDataContainer, System.Web.Routing.RouteCollection)'.

I'm registering everything using the sample code from the docs.

private void RegisterAutofacMVC(ContainerBuilder builder)
{
    // Register your MVC controllers. (MvcApplication is the name of
    // the class in Global.asax.)
    builder.RegisterControllers(typeof(AccountController).Assembly);

    // OPTIONAL: Register model binders that require DI.
    builder.RegisterModelBinders(typeof(AccountController).Assembly);
    builder.RegisterModelBinderProvider();

    // OPTIONAL: Register web abstractions like HttpContextBase.
    builder.RegisterModule<AutofacWebTypesModule>();

    // OPTIONAL: Enable property injection in view pages.
    builder.RegisterSource(new ViewRegistrationSource());

    // OPTIONAL: Enable property injection into action filters.
    builder.RegisterFilterProvider();
}

And I have some setup code using some of my custom solutions.

private void SetupMVC(IAppBuilder app, IContainer container)
{
    DependencyResolver.SetResolver(new Autofac.Integration.Mvc.AutofacDependencyResolver(container));

    app.UseAutofacMiddleware(container);
    app.UseAutofacMvc();

    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);

    AreaRegistration.RegisterAllAreas();
    ModelBinders.Binders.DefaultBinder = new CustomModelBinder();

    ValueProviderFactories.Factories.Remove(ValueProviderFactories.Factories.OfType<JsonValueProviderFactory>().FirstOrDefault());
    ValueProviderFactories.Factories.Add(new JsonNetValueProviderFactory());
}

Also, I have some ASP.NET SignalR hubs which require me to use Owin, and I'm trying to use Autofac there too.

private void RegisterAutofacSignalR(ContainerBuilder builder)
{
    builder.RegisterHubs(typeof(TermekBetoltesHub).Assembly);
}

private void SetupSignalR(IAppBuilder app, IContainer container)
{
    var hubConfiguration = new HubConfiguration()
    {
        Resolver = new AutofacDependencyResolver(container),
        EnableDetailedErrors = true
    };

    app.MapSignalR(hubConfiguration);

    // To add custom HubPipeline modules, you have to get the HubPipeline
    // from the dependency resolver, for example:
    var hubPipeline = hubConfiguration.Resolver.Resolve<IHubPipeline>();
    hubPipeline.AddModule(new CustomErrorModule());
}

I have a quite strong feeling that I'm mixing a few concepts but I cannot wrap my head around all these stuff and make them work together nicely.

Could anyone provide me some hints or tips what I should check?

Enable properties on MVC models to be injected during model binding

From @alexmg on January 22, 2014 14:5

From [email protected] on February 08, 2011 14:41:08

For the past year and half, I've been using an extension method and a generic model binder combination that allow me to inject view models on am Mvc ActionResult.

For example - say I have a view model called "SimpleOrderModel" that injects a repository (imho a controller shouldn't understand how to load and save a model - it's the model's job).

Therefore, I should be able to create an action result that looks like this:

[HttpPost]
public ActionResult Configure(SimpleOrderModel simpleOrderModel)
{
  if(ModelState.IsValid)
  {

To go along with this code, I have a registration extension where the call looks like this:

builder.RegisterInjectedModel<SimpleOrderViewModel>().InstancePerDependency();

I find this incredibly useful.

I have this in my local repo and I've included a patch file of the implementation. I could also move this to a named branch or check it my fork depending on the process of including it.

Attachment: autofacmvc_iocmodelbinder.patch

Original issue: http://code.google.com/p/autofac/issues/detail?id=292

Copied from original issue: autofac/Autofac#292

Request scope is set twice when using Autofac.Integration.Mvc.Owin

From @rosslyn-benfoster on July 15, 2014 17:15

Due to how MVC registers routes, the request scope is actually set twice the first time the application runs.

During route registration MVC invokes the dependency resolver to get an IControllerFactory instance which in turn creates the request scope using RequestLifetimeHttpModule. Then the middleware is invoked and a new request scope is set.

It's not a major issue but thought it was worth pointing out as it does mean the first scope will never be disposed.

I came across this whilst trying to implement a scope per request using Owin middleware only. Due to MVC invoking the dependency resolver so early on, it was throwing exceptions due to the Owin environment having not yet been initialized.

Copied from original issue: autofac/Autofac#555

RequestLifetimeProvider stored as static reference in ASP.NET MVC

From @tillig on July 9, 2014 20:31

Whenever you new up a RequestLifetimeScopeProvider in the MVC integration, it sets that provider as a static reference with the RequestLifetimeHttpModule:

public RequestLifetimeScopeProvider(ILifetimeScope container)
{
  if (container == null) throw new ArgumentNullException("container");
  _container = container;
  RequestLifetimeHttpModule.SetLifetimeScopeProvider(this);
}

The problem is that if you happen to want to have more than one AutofacDependencyResolver or RequestLifetimeScopeProvider for whatever reason, they effectively become singletons - creating a new one replaces the disposal semantics for the old one.

It might be better to have RequestLifetimeScopeProvider implement IDisposable and update RequestLifetimeHttpModule to allow a queue of providers. During construction, the RequestLifetimeScopeProvider could add itself to the queue; during disposal it would remove itself from the queue.

Copied from original issue: autofac/Autofac#549

Update to support .NET 4.5

During the port to .NET Core it appeared Autofac core would only support .NET 4.5.1 and higher so this package was updated accordingly. Now the dust has settled, we may be able to change this package to support .NET 4.5 since we got core Autofac to also support it.

Glimpse interferes with ExtensibleActionInvoker on MVC5

From @alexmg on January 22, 2014 14:27

From travis.illig on July 23, 2013 02:14:11

When Glimpse is disabled, the ExtensibleActionInvoker is able to inject parameters into controller actions without issue. When it is enabled, injection fails.

This can be reproduced in the "Remember.Web" sample application in the Autofac solution:

  • Start the application.
  • Click the "Enable Glimpse" link.
  • Click the button to turn Glimpse on.
  • Navigate back to the home page of the demo app.
  • Go to the "ExtensibleActionInvoker Integration Tests" page.
  • Run the "Simple Controller Action Parameter Injection" tests.

An exception will appear; details below.

It appears that Glimpse is attempting to wrap/replace the action invoker as part of its debugging integration. Note the stack trace in the application never runs through Autofac the way it should if ExtensibleActionInvoker is in place.

Related: a similar issue has been reported (appended to Issue #351 ) where the AutofacFilterAttributeFilterProvider is also running into trouble, most likely for similar reasons.

Exception re: ExtensibleActionInvoker below:

Server Error in '/' Application.

Cannot create an instance of an interface.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.MissingMethodException: Cannot create an instance of an interface.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[MissingMethodException: Cannot create an instance of an interface.]
System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0
System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +113
System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +232
System.Activator.CreateInstance(Type type, Boolean nonPublic) +83
System.Activator.CreateInstance(Type type) +6
System.Web.Mvc.DefaultModelBinder.CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) +183
System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +564
System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +416
Castle.Proxies.DefaultModelBinderProxy.BindModel_callback(ControllerContext controllerContext, ModelBindingContext bindingContext) +44
Castle.Proxies.Invocations.DefaultModelBinder_BindModel.InvokeMethodOnTarget() +191
Castle.DynamicProxy.AbstractInvocation.Proceed() +117
Glimpse.Core.Extensibility.CastleInvocationToAlternateMethodContextAdapter.Proceed() +48
Glimpse.Core.Extensibility.ExecutionTimer.Time(Action action) +195
Glimpse.Core.Extensions.AlternateMethodContextExtensions.TryProceedWithTimer(IAlternateMethodContext context, TimerResult& timerResult) +198
Glimpse.Core.Extensibility.AlternateMethod.NewImplementation(IAlternateMethodContext context) +45
Glimpse.Core.Extensibility.AlternateTypeToCastleInterceptorAdapter.Intercept(IInvocation invocation) +183
Castle.DynamicProxy.AbstractInvocation.Proceed() +483
Castle.Proxies.DefaultModelBinderProxy.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +219
System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) +317
System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor) +117
System.Web.Mvc.Async.<>c__DisplayClass25.b__1e(AsyncCallback asyncCallback, Object asyncState) +446
System.Web.Mvc.Async.WrappedAsyncResult1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130 System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state) +302 System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__17(AsyncCallback asyncCallback, Object asyncState) +30 System.Web.Mvc.Async.WrappedAsyncResult1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state) +382
System.Web.Mvc.Async.WrappedAsyncResult1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130 System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +317 System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +15 System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__2(AsyncCallback asyncCallback, Object asyncState) +71 System.Web.Mvc.Async.WrappedAsyncResult1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +249
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +50
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +301
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155


Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18045

Original issue: http://code.google.com/p/autofac/issues/detail?id=451

Copied from original issue: autofac/Autofac#451

how can i implement autofac on mvc 5.2 and 4.5.2 framework ?

In this page :https://www.nuget.org/packages/Autofac.Mvc5/
In Discription told :

Dependencies
Autofac (>= 4.0.0 && < 5.0.0)
Microsoft.AspNet.Mvc (>= 5.1.0 && < 6.0.0)

and Updated to .NET 4.5.1, Autofac 4 compatibility

in my project i used mvc 5.2 and dot net 4.5.2

how can implement Autofac on my project ?

Quick Start MVC (this page : http://autofac.readthedocs.io/en/latest/integration/mvc.html#quick-start)

told

  // Register your MVC controllers.
  builder.RegisterControllers(typeof(MvcApplication).Assembly);

but in my project get an error "Could not be found"

how can fix it ?

Project still under active development?

I've identified a couple of performance issues with how the Autofac MVC library injects filters and parameter values which I'd like to try and address. Before I spend time creating and submitting a PR I'd like to know- will it be considered and if it meets the projects standards, merged?

How do you register a custom action invoker?

Hello,

On a more practical front, how are filter dependencies injected?

I'd done something along these lines based on Castle Windsor, but I had to replace the IActionInvoker based on ControllerActionInvoker in order to do so.

This, and a possibly couple of other services, potentially provided via, in this case, the AutofacDependencyResolver.

For example,

using System.Linq;
using System.Web.Mvc;

namespace Kingdom.Web.Mvc
{
    using Castle.Windsor;

    public class WindsorControllerActionInvoker : ControllerActionInvoker, IWindsorActionInvoker
    {
        private IWindsorContainer Container { get; }

        public WindsorControllerActionInvoker(IWindsorContainer container)
        {
            Container = container;
        }

        private void InjectFilter<T>(T obj)
        {
            // InjectObject is an extension method of mine, basically handles the reflection, introspection, and property setters; fairly standard looking stuff
            Container.InjectObject(obj);
        }

        protected override FilterInfo GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
        {
            var filterInfo = base.GetFilters(controllerContext, actionDescriptor);

            // We must treat each of the Filter types individually.
            filterInfo.AuthorizationFilters.ToList().ForEach(InjectFilter);
            filterInfo.ActionFilters.ToList().ForEach(InjectFilter);
            filterInfo.ResultFilters.ToList().ForEach(InjectFilter);
            filterInfo.ExceptionFilters.ToList().ForEach(InjectFilter);

            return filterInfo;
        }
    }
}

Thanks!

Register generic type of model binder

From @TerraVenil on January 10, 2015 12:4

I can't get the Autofac model binding for MVC to work with generic model binder and I think it should be enhanced. For example, in MVC I can write

public class SomeBinder<T> : IModelBinder {}

public ActionResult Update([ModelBinder(typeof(SomeBinder<List<SomeClassA>>))]List<SomeClassA> parameters)
and also register through global model binders as

ModelBinder.Binders.Add(typeof(List<SomeClassA>), new SomeBinder<List<SomeClassA>());

now update method look like

public ActionResult Update(List<SomeClassA> parameters)

and all works fine. But if I am trying to do the same things through Autofac, remove global initialization and use ModelBinderType attribute

[ModelBinderType(typeof(List<SomeClassC>))]
[ModelBinderType(typeof(List<SomeClassB>))]
[ModelBinderType(typeof(List<SomeClassA>))]
public class SomeBinder<T> : IModelBinder {}

and register it when container is build

builder.RegisterModelBinders(Assembly.GetExecutingAssembly()); builder.RegisterModelBinderProvider();

but unfortunately Autofac doesn't intercepting http request to controller and not injecting model binder. I find some workaround using generic model binder through inheritance like that

[ModelBinderType(typeof(List<SomeClassA>))]
public class SomeListClassABinder : SomeModelBinder<List<ClassA>>

but as from my point of view it's not very elegant solution. Why Autofac can't resolve type T? As we already have that type T inside model binder type attribute typeof(List<SomeClassA>)?

Copied from original issue: autofac/Autofac#612

can name injection be supported

If multiple instances implement the same interface and multiple names are registered at the time of registration, can name be used to distinguish one implementation of the injected interface in the injected concrete implementation class

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.