Coder Social home page Coder Social logo

examples's Introduction

Autofac Examples

Example projects that consume and demonstrate Autofac functionality and integration.

Build status

Reading the Examples

The examples in the repo are always for the latest Autofac versions and libraries. Look at the tags on this repo to see examples for older and/or deprecated functionality.

The examples attempt to stick pretty close to the Autofac documentation so it helps to have that available.

Open this repo in Visual Studio Code.

Building the Examples

The Examples.sln file has all the samples in it except the ServiceFabric example. ServiceFabric is in a child directory and has its own solution.

examples's People

Contributors

alexmg avatar alsami avatar johnmwright avatar mart-bogdan avatar monsieurleberre avatar tbenade 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  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  avatar  avatar  avatar  avatar

Watchers

 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

examples's Issues

Injecting a controller as a dependency

Brief explanation of why I need to do this.
We're generating PDFs from HTML, and we need to render Razor views to do so. After much exploration, I came across several documents that say it's impossible without an actual controller. There is, however, two standalone Razor view libraries, however, they're both abandoned, and the latest one has an outstanding issue that prevents testing. Because of that, to test the service, we had to create a new MVC project. We just called it PdfTest and hope that it's a one off. But that doesn't fix the problem of dependencies in the actual MVC project now that we need to inject controllers.

Our constructor looks like

public PdfService(ControllerBase controller, string viewPath)

Service Fabric Autofac example for AspNet DotNetCore 3.1+

No examples on how to use Autofac in AspNet Core (DotNet Core 3.1+) web applications that run in Service Fabric

The repo at https://github.com/autofac/Examples/tree/master/src/ServiceFabricDemo/AutofacServiceFabricDemo hasn't been updated in 3 years. A lot has changed since then.

For instance, Startup.cs must have a void ConfigureServices(IServiceCollection services) method. Returning IServiceProvider is not valid anymore after DotNetCore 3.1+

I have created the following branch with a web app running the latest DotNetCore, that uses service fabric and Microsoft Dependency Injection. See here

It fulfills all the requirements (DI, reading appsettings, clean change of environment for testing, TestServer with possibility to overwrite DI registrations for mocks, etc.). Please feel free to have a look and if there's any way to add Autofac to that sample I'll be happy to contribute.

There are unanswered questions in StackOverflow about the same:
https://stackoverflow.com/questions/59980827/service-fabric-aspnet-core-3-1-autofac-webhostbuilder
https://stackoverflow.com/questions/64260534/how-to-use-service-fabric-service-with-aspnet-core-webapi-and-autofac-and-run-te
https://stackoverflow.com/questions/64278765/how-to-use-autofac-with-iwebhost

Desired Solution

A basic example on how to register Autofac with a WebHostBuilder (if possible), and where to register dependencies in a service fabric app would be enough.

Alternatives You've Considered

The alternative I've considered is not to use Autofac, but if I could help in any way to find out how to do it or to suggest something, I'll do that.

Remember.Web: does not match documentation any more

From @AGBrown on July 13, 2014 14:54

Versions:

Issue

When trying to use the Remember.Web to understand the Mvc-Integration wiki documentation, the sample code does not work when an [Authorize] (or custom authorize) attribute is applied to an action, due to problems with the web.config authentication/forms element. This specifies the loginUrl as ~/Account/LogOn (it should be ~/Account/Login). The sample project also doesn't provide an easy way to set a login cookie and authorize a user to try out the CustomAuthorize attribute in the wiki documentation.

Impact

The sample Remember.Web doesn't demonstrate the documentation on the Mvc-Integration wiki page. The wiki page references the sample as it ...

... demonstrates many of the aspects of MVC that Autofac is used to inject.

Proposed solution

The fix for this is quite simple, but it also requires #550 to be fixed.

With a few small changes the sample Remember.Web Mvc application could be made to fit in with the wiki at Mvc-Integration and demonstrate the following:

  • Model binding for the logon form with LoginFormBinder (currently working) with IAuthenticationService injection (currently working)
  • Custom authorization attribute (with injection, as per the wiki page) that works with a login cookie to redirect unauthorized users, and accept authorized users.
  • Redirection to the login url, which therefore demonstrates all the above

The changes that are required:

  1. Fix Issue #550
  2. Update the web.config authentication/forms element
  3. Add a CustomAuthorizeAttribute as per the wiki
  4. Add [CustomAuthorize] and [AllowAnonymous] to the AccountController (as per the current Mvc template application in VS2013)
  5. Set the Remember.Web.csproj.user file to launch Account/LoginSuccess as the StartPageUrl

I will post an example changeset as a follow up to this issue to AutofacABContrib branch dev-552. In the example I have also split out "validation" by the IAuthenticationManager (renamed in the commit to ICaptchaManager and "authentication" performed using FormsAuthentication in the AccountController Please let me know if you would like me to create a pull request for the branch.

Copied from original issue: autofac/Autofac#552

Generalize the plugin demo for using external plugins not configured at compile time.

The demo ConfigurationExample define both internal and external dependencies using a configuration file autofac.json
In other scenarios, the plugins are loaded in external folder like a tree and are not defined at compile time.
plugin folder Example:

----plugins
     |plugin1
     |   |-- plugin1.dll
     |   |--plugin1_nuget_lib.dll  //nuget package used by plugin1
     |plugin2
         | --plugin2.dll
         |...

So, autofac load the plugins from the assemblies in the plugin folder and manage its dependencies.
It's nice if we have a demo for such scenario

Generic Host no longer calls ConfigureTestContainer for container overrides

I have Integration tests, which uses WebApplicationFactory net core interface.
Earlier netcore versions <3.0 has a way to override custom container registrations but once switched to generic host startup mode. The method override ConfigureTestContainer no longer get called. What do you recommend in terms of overriding the registrations in Autofac container for unit testing.

Below mehod is not called anymore in net core 3.

 .ConfigureTestContainer<ContainerBuilder>(containerBuilder =>
            { }

The order in which application bootstrap for IntegrationTests are:
Startup -> ConfigureServices
TestStartup -> ConfigureServices (Method Override if defined)
TestStartup -> ConfigureTestServices
Startup -> ConfigureContainer
TestStartup -> ConfigureTestContainer (Not called since netcore 3.0 upgrade with generic host usage)

There is a github issue on dotnet github page dotnet/aspnetcore#14907
but cannot find the solution.

Example of using autofac in a unit test project

Hi,

First of all, great work on Autofac - I love it!

I was just browsing through your examples and noticed there isn't an example of how autofac is best used in an integration test project. Is there any suggested guidance on how best to go about this?

In a current project I have this inheritance-based approach which I knocked up in a hurry:

using System;
using System.Diagnostics;
using System.Reflection;
using Autofac;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace SomeTests
{
    public class TestBase 
    {
        private IContainer _autofacContainer;
        protected IContainer AutofacContainer
        {
            get
            {
                if (_autofacContainer == null)
                {
                    var builder = new ContainerBuilder();

                    // Repositories
                    builder.RegisterType<CompanyDataDb>().As<CompanyDataDb>().InstancePerLifetimeScope();

                    // Register the CompanyDataRepository for property injection not constructor allowing circular references
                    builder.RegisterType<CompanyDataRepository>().As<ICompanyDataRepository>()
                           .InstancePerLifetimeScope()
                           .PropertiesAutowired(PropertyWiringOptions.AllowCircularDependencies);

                    // Other wireups....

                    var container = builder.Build();

                    _autofacContainer = container;
                }

                return _autofacContainer;
            }
        }

        protected ICompanyDataRepository CompanyDataRepository
        {
            get
            {
                return AutofacContainer.Resolve<ICompanyDataRepository>();
            }
        }

        protected CompanyDataDb CompanyDataDb
        {
            get
            {
                return AutofacContainer.Resolve<CompanyDataDb>();
            }
        }
    }
}

All the tests inherit from this class. This works but I kind of doubt it's a good example of good practice - is there a better example out there I could refer to?

MSB4126 error when executing dotnet restore

Error when hitting dotnet restore

C:\Users\Admin\Source\Repos\Examples\Examples.sln.metaproj : error MSB4126: The specified solution configuration "Debug|X64" is invalid. Please specify a valid solution configuration using the Configuration and Platform properties (e.g. MSBuild.exe Solution.sln /p:Configuration=Debug /p:Platform="Any CPU") or leave those properties blank to use the default solution configuration. [C:\Users\Admin\Source\Repos\Examples\Examples.sln]

When I try to build the solution, MVC and Webform projects are unavailable and EnterpriseLibraryExample.MvcApplication has missing references.

.NET Command Line Tools (2.1.2)

Product Information:
Version: 2.1.2
Commit SHA-1 hash: 5695315371

Runtime Environment:
OS Name: Windows
OS Version: 10.0.16299
OS Platform: Windows
RID: win10-x64
Base Path: C:\Program Files\dotnet\sdk\2.1.2\

Microsoft .NET Core Shared Framework Host

Version : 2.0.3
Build : a9190d4a75f4a982ae4b4fa8d1a24526566c69df

How the mvc example support the dependency resolve?

I am reading the documentation
https://autofaccn.readthedocs.io/en/latest/faq/per-request-scope.html#id2
The handling of the creation of the request-level lifetime scope and the cleanup of that scope are generally dealt with via the Autofac application integration libraries for your application type.
I am trying to figure out how the autofac resolve the instance.

I found the registration code for IViewDependency
https://github.com/autofac/Examples/blob/master/src/MvcExample/Global.asax.cs#L75.
And here is a property with IViewDependency type in class CustomViewPage
https://github.com/autofac/Examples/blob/master/src/MvcExample/CustomViewPage.cs#L14

As far as I have learnt that we can resolve instance by these ways:
1.constructor injection
2.property injection
3.manually resolve by Resolve method

Since the there is a Dependency property in CustomViewPage class is with IViewDependency type, I supposed that you will use property injection to do the resolve work. However, I did not find the property injection code in the mvc example which should be implemented as mentioned here

What I found is the following code
https://github.com/autofac/Examples/blob/master/src/MvcExample/Global.asax.cs#L60

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

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

As literally understanding, I do not think the above code could support property injection for IViewDependency.
Does anyone knows how the resolve work for IViewDependency?

Why Autofac could not run when using reflection to inject it ON .NET 6

Describe the Bug

I have used Autofac to inject and inverse by this following way. But it could not effect. It was error when I use the interface in controller as injection, the console and website show me that I do not inject the correspond type for it.
NOTES: This way is correct to inject ON .NET5 and .NET 3.x version, but .NET6.

Steps to Reproduce

In .NET6, just write a test demo project, just like I use to inject the service. and the issues will reproduce.

public static void Configure(WebApplicationBuilder builder)
        {
            builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
            builder.Host.ConfigureContainer<ContainerBuilder>(containerBuilder =>
            {
                containerBuilder.RegisterModule(new TestModule());
            }
        }
public class TestModule : Autofac.Module{
     protected override void Load(ContainerBuilder builder)
        {
            Assembly[] assemblies = DependencyContext.Default.RuntimeLibraries
                .Where(a => a.Name.StartsWith("Test"))
                .Select(o => Assembly.Load(new AssemblyName(o.Name))).ToArray();

            builder.RegisterAssemblyTypes(assemblies)
            .Where(t => t.GetCustomAttribute<SingleInstanceAttribute>() != null)
            .AsImplementedInterfaces()
            .SingleInstance()
            .PropertiesAutowired();
        }
}

Expected Behavior

It should correctly inject the service.

Exception with Stack Trace

Microsoft Visual Studio Debug Console
Autofac.Core. DependencyResolutionException: An exception was thrown while activating TestDemo.Controllers.AdminController.
---〉Autofac.Core. DependencyResolutionException: None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder’on type TestDemo.Controllers.AdminController’ can be invoked with the available services and parameters:
Cannot resolve parameter ' TestDemo.ITestService testService’of constructor 'Toid .ctor'(TestDemo.ITestService)’.
at Autofac.Core.Activators.Reflection.ReflectionActivator. etAllBindings(ConstructorBinder[] availableConstruoct
ors,IComponentContext context,IEnumerable` 1 parameters)
at Autofac.Core.Activators.Reflection.ReflectionActivator.ActivateInstance(TComponentContext context,,IEmumeratle`1 parameters)
at Autofac.Core.Activators.Reflection.Reflectionctivator.<ConfigurePipeline>b_11_0(ResolveRequestContext etort,Action 1 next)
.. at Autofac.Core.Resolving.Pipeline.ResolvePipelineBuilder.(c_DisplayClassl4 0.BuildPipelineb_1(ResolveRequestContext ctxt)
at Autofac.Core.Resolving.Middleware.DisposalTrackingMiddleware.Execute(ResolveRequestContext context,,Action 1
next)
at Autofac.Core.Resolving.Pipeline.ResolvePipelineBuilder.<>c_DisplayClass14_0.(BuildP'ipeline>b_l(ResolveRegqu
estContext ctxt)
at Autofac.Builder.RegistrationBuilder 3.c_DisplayClass41_0. Propertieskutowired>b_Q)(esolveRequestContertctxt,Action 1 next)
at Autofac.Core.Resolving.Pipeline.ResolvePipelineBuilder.(c_DisplayClass14_0.BuildPipeline)b_1(ResolveReqpestContext ctxt)
.atAutofac.Core.Resolving.Midleware.ActivatorErrorHandlingMiddeware. Execute(ResolveRequestContext context,kotion 1 next)
—-- End of inner exception stack trace ---
at Autofac.Core.Resolving .Middleware.hctivatorErrorHandlingMidleware.Execute(ResolveRequestContext context,Ao
tion`1 next)
at Autofac.Core. Resolving.Pipeline.ResolvePipelineBuilder.<>c_DisplayClass14_0.<BuildPipeline)b_1(ResolveRequ

Dependency Versions

Autofac:

Autofac, Version=6.0.0.0
Autofac.Extensions.DependencyInjection, Version=7.2.0.0
Autofac.Extras.DynamicProxy, Version=6.0.0

Additional Info

Why Autofac could not run when using reflection to inject it ON .NET 6

Describe the Bug

Steps to Reproduce

public class ReproTest
{
  [Fact]
  public void Repro()
  {
    var builder = new ContainerBuilder();
    var container = builder.Build();
    Assert.NotNull(container);
  }
}

Expected Behavior

Exception with Stack Trace

Put the exception with stack trace here.

Dependency Versions

Autofac:

Autofac, Version=6.0.0.0
Autofac.Extensions.DependencyInjection, Version=7.2.0.0

Additional Info

AutofacModule Load(...) method has outdated comment

In the master branch, the Load method in the AutofacModule has a comment that reflects a previous configuration, namely:

The generic ILogger service was added to the ServiceCollection by ASP.NET Core. It was then registered with Autofac using the Populate method in ConfigureServices.

However, the current Startup.cs reflects the following method signature:
void ConfigureContainer(ContainerBuilder builder)
void ConfigureServices(IServiceCollection services)

The latter method does not include the previously specified Populate() call.

You might want to change the comment to acknowledge that, on the contrary, none of the IServiceCollection services are available to be resolved until the startup configuration has completed (well after the Module.Load() implementation call).

The good news is that actual DI (such as to controller constructors) is of course still resolving fine with the module pattern. A problem arises if someone trusts the comment and attempts in the context of debugging/experimentation to build the container and try to resolve IValuesService within the load method, similar to what is in numerous examples in the manual. (This problem does not exist with the alternative pattern of the Populate(IServiceCollection services) call prior to adding Autofac.builder registrations.)

You might consider shifting registration of the logger in your sample to the Load method (i.e. to the Autofac container) so that it is available for casual experimentation. Alternatively, to change the example to eliminate the dependency of the ValuesService on ILogger<>, though that is one of the core scenarios.

autofac + mvc + owin example

Is there a possibility of getting the example MvcApplication updated to incorporate owin with entity framework.

I have followed all the official docs, looked at online samples, but this simply is not working.

The SigninManager successfully authenticates my login, however every request to an Authroized controller redirects back to the login form.

Rapidly losing hope in autofac's support for owin.

No connection could be made because the target machine actively refused it 127.0.0.1:25665

To test the https://github.com/autofac/Examples/tree/master/src/MvcExample
We also need deploy another new site under IIS for wcf
https://github.com/autofac/Examples/blob/master/src/MvcExample/Web.config#L68

<system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="BasicHttpBinding_IService" />
      </basicHttpBinding>
    </bindings>
    <client>
      <endpoint address="http://localhost:25665/HostFactoryService.svc" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IService" contract="HostFactoryService.IService" name="BasicHttpBinding_IService" />
    </client>
  </system.serviceModel>
  1. set the site folder as Autofac\Examples\src\WcfExample
  2. add bindings for site
    image
  3. build the https://github.com/autofac/Examples/tree/master/src/WcfExample

Remember.Web: IContainerProviderAccessor exception

From @AGBrown on July 12, 2014 20:59

Using:

Steps to reproduce

  1. Clone the repository from github.
  2. Build (Nugets restored on build)
  3. Run tests (all pass other than those expected due to issues 272 & 397)
  4. Run Remember.Web.

Exception seen:

The exception below is shown on browsing to the home page. (It is also seen when browsing to the account pages).


Server Error in '/' Application.

This module requires that the HttpApplication (Global Application Class) implements IContainerProviderAccessor. 
  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.InvalidOperationException: This module requires that the HttpApplication (Global Application Class) implements IContainerProviderAccessor.

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: 

[InvalidOperationException: This module requires that the HttpApplication (Global Application Class) implements IContainerProviderAccessor.]
   Autofac.Integration.Web.ContainerDisposalModule.Init(HttpApplication context) +173
   System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers) +418
   System.Web.HttpApplication.InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context) +172
   System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr appContext, HttpContext context) +336
   System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr appContext) +296

[HttpException (0x80004005): This module requires that the HttpApplication (Global Application Class) implements IContainerProviderAccessor.]
   System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +9885060
   System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +101
   System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +254

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

Copied from original issue: autofac/Autofac#550

ConfigurationExamplePlugin example code assembly code could not be found

Hi I am trying your example code for configuration plugins

https://github.com/autofac/Examples/tree/master/src/ConfigurationExample

When trying to run the example solution I face this error

Unhandled Exception: System.InvalidOperationException: The type 'ConfigurationExamplePlugin.ExternalPlugin, ConfigurationExamplePlugin' could not be found. It may require assembly qualification, e.g. "MyType, MyAssembly".
at Autofac.Configuration.Core.ConfigurationExtensions.GetType(IConfiguration configuration, String key, Assembly defaultAssembly) in C:\projects\autofac-configuration\src\Autofac.Configuration\Core\ConfigurationExtensions.cs:line 221

Stating the assembly can not be found.

If I reference the external plugin in the ConfigurationExample.csproj then the plugin loads fine. but this defeats the point of loading it from a configuration.json also it is not logical that the IoC should be aware of external code like this.

I did bump the version of dotnetSDK in the global.json to match my installed version of 2.2.103. But I can not imagine this is the issue. Am I missing something? I am trying to run on an ubuntu platform.

Unable to compile in VS 2017

I have the latest VS 2017 community edition. When I tried to compile this solution I am getting the following error: The current .NET SDK does not support targeting .NET Standard 2.0. Either target .NET Standard 1.6 or lower, or use a version of the .NET SDK that supports .NET Standard 2.0.

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.