GithubHelp home page GithubHelp logo

autofac / documentation Goto Github PK

View Code? Open in Web Editor NEW
69.0 12.0 121.0 4.24 MB

Usage and API documentation for Autofac and integration libraries

Home Page: http://autofac.readthedocs.org

License: MIT License

C# 11.63% JavaScript 88.37%

documentation's Introduction

Autofac Documentation

Usage and API documentation for Autofac and integration libraries.

Documentation Status Open in Visual Studio Code

Check out the Autofac documentation at docs.autofac.org!

Updating the User Documentation Site

User documentation is viewable at https://docs.autofac.org (a CNAME to https://autofac.readthedocs.io). It is stored in the /docs folder in this source repo.

To build the docs and see them locally, you need to follow the Getting Started docs on Read The Docs so you get Python and Sphinx installed.

The docs are written in reStructuredText, which is very similar to Markdown but not quite. References below.

Updates to the documentation checked into the /docs folder will automatically propagate to Read The Docs. No build or separate push is required.

There is support for converting PlantUML (.puml) documents into PNG images for easier diagramming. Run npm watch to start the generation. Diagrams only get generated on change and will not be rebuilt/regenerated without a change.

Building

  1. Install Python 3.x
  2. Install Sphinx: pip install sphinx sphinx-autobuild
  3. Build the docs after you edit them. There should be NO errors or warnings: make html

References

Updating API Documentation

The API documentation is hosted on autofac.github.com and the rendered/built docs are in there. This repository has the project that enables building the doc (a manual process) but publishing is a separate step.

The Placeholder project holds references to the various Autofac packages to document. Use that as the basis for gathering the list of doc sources.

Adding/Updating Doc Sources

  1. Add or update the NuGet package to the Placeholder project.
  2. Open the app.config for the Placeholder project and copy the assembly binding redirects to the appropriate location in Documentation.shfbproj. These are required for the documentation project to obey redirects.

Building the Documentation

Run msbuild Documentation.proj to kick off the build. This will restore required NuGet packages, build the Placeholder project, and run documentation on the Autofac referenced assemblies. You may need to install the Visual Studio 2017 build tools to get this to work. If you see errors/failing about unrecognized ToolsVersion - that's the missing build tools.

The build generates a lot of warnings. These indicate where we're missing documentation. (If you're looking to submit a PR, better API docs is a good thing...)

Build output gets put in the artifacts folder.

The contents of artifacts\doc\Website is what gets copied to the autofac.github.com repo.

documentation's People

Contributors

abug avatar airn5475 avatar akselarzuman avatar alexmg avatar alistairjevans avatar alsami avatar astef avatar aydjay avatar babrekel avatar blairconrad avatar brondahl avatar egasimov avatar eliranlevi avatar geertvl avatar gldraphael avatar hoflnauix avatar intexx avatar jacobsnyder avatar jasontheprogrammer avatar mathi82 avatar metalfork avatar mikesigs avatar mjamro avatar ncubed avatar phillipsj avatar snowbear2014 avatar steveoh avatar tillig avatar tonyvalenti avatar weelink 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

Watchers

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

documentation's Issues

.NET Core 3.0 Docs needs update

.NET Core 3.0 Doc looks deprecated
https://autofac.readthedocs.io/en/latest/integration/aspnetcore.html#asp-net-core-3-0-and-generic-hosting

I followed the steps and the first area I got stuck it at
builder.RegisterModule(new AutofacModule());

There is no AutofacModule class, is it my responsibility to create this class by inheriting IModule?
I have added Autofac.Extensions.DependencyInjection 5.0.1

Am I missing any step?

A quick code for Autofac integration in .NET Core 3.0 would be appreciated, as I am stuck on this. Probably many others are too.
Thanks in advance.

Documentation on ContravariantRegistrationSource

Autofac has a hidden gem ContravariantRegistrationSource but there is no documentation on it so folks don't know about it. Some docs with an example explaining usage (and why you'd want to use it) would be great.

Pipelines Documentation

Need to write documentation on how pipelines work and how people can define and attach their own middleware.

This will be targeted at advanced users.

Additional Guidance for Custom Metadata Usage

Problem Statement

It's unclear from the metadata docs on how to use an attribute that's created outside the filtering scenario and instead to lookup values on the metadata either during or before resolution.

For instance modifying the WeakTypedAttributeScenarioTestFixture to demonstrate what I was trying:

            // arrange
            var builder = new ContainerBuilder();
            builder.RegisterModule<AttributedMetadataModule>();
            builder.RegisterType<CombinationalWeakTypedScenario>().As<ICombinationalWeakTypedScenario>();

            // act
            var items = builder.Build().Resolve<IEnumerable<Lazy<ICombinationalWeakTypedScenario, CombinationalWeakAgeMetadataAttribute>>>();

            // assert
            Assert.Single(items);
            Assert.Single(items.Where(p => p.Metadata.Age == 42));

But this leads to a Autofac.Core.DependencyResolutionException : The type 'CombinationalWeakAgeMetadataAttribute' cannot be used as a metadata view. A metadata view must be a concrete class with a parameterless or dictionary constructor. error.

If I add a parameterless constructor to the type, then it appears to work in the test project (though I'm having trouble making this work in my own project with an enum instead of an int/string).

Anyway, it'd be great to see more examples for different setups in the documentation for using these types of more strongly-typed custom attributes.

Desired Solution

More guidance on using strongly-typed custom metadata within autofac. Especially around metadata lookup before resolution, if possible?

Update Blazor integration docs with the latest method signatures

autofac/Autofac.Extensions.DependencyInjection#69 - Since writing the Blazor integration docs the methods on WebAssemblyHostBuilder have changed. The docs don't appear to be correct anymore and need to be updated, possibly with more robust/better examples and/or an explanation about how the methods have changed over time to help folks migrating.

I'm not personally a Blazor user - it'd be great to see someone who uses Blazor and the Autofac integration (by way of the standard ASP.NET Core integration points, which is how Autofac integrates) write the docs they'd like to see. Nothing we're doing is "Autofac specific" other than just using the AutofacServiceProviderFactory.

Outdated documentation for asp.net core 2.2

When using asp.net core 2.2 without ConfigureContainer documentation is wrong.

Particularly there is not return type in ConfigureServices method since the method signature in different from the one in the documentation

public void ConfigureServices(IServiceCollection services)
{
}

where as in documentation of autofac


 // ConfigureServices is where you register dependencies. This gets
  // called by the runtime before the Configure method, below.
  public IServiceProvider ConfigureServices(IServiceCollection services)
  {
    // Add services to the collection.
    services.AddMvc();

    // Create the container builder.
    var builder = new ContainerBuilder();

    // Register dependencies, populate the services from
    // the collection, and build the container.
    //
    // Note that Populate is basically a foreach to add things
    // into Autofac that are in the collection. If you register
    // things in Autofac BEFORE Populate then the stuff in the
    // ServiceCollection can override those things; if you register
    // AFTER Populate those registrations can override things
    // in the ServiceCollection. Mix and match as needed.
    builder.Populate(services);
    builder.RegisterType<MyType>().As<IMyType>();
    this.ApplicationContainer = builder.Build();

    // Create the IServiceProvider based on the container.
    return new AutofacServiceProvider(this.ApplicationContainer);
  }

Diagnostics Documentation

Docs needed for:

  • Basic info on how to capture diagnostics
  • Documentation for advanced users that might need to create their own tracers.

Misleading information for ASP.NET Core

Under this section

No manual controller registration. You used to be required to register all of your controllers with Autofac so DI would work. The ASP.NET Core framework now automatically passes all controllers through service resolution so you don't have to do that.

This information is misleading. It states that you "don't have to" register your controller with Autofac, which IMHO, is different than "you can't register your controller with Autofac". The latter of these 2 behaviors is what I've witnessed.

Scenario:

  • Create a named registration
  • Create a controller registration that instantiates the controller by resolving the named registration as a dependency
  • Put a breakpoint in the controller's constructor and witness that your named registration is not what was injected

docs.autofac.org -> https

I see that in 067be33 the url has been changed https://autofac.readthedocs.io/, but that's not needed.

https://docs.autofac.org should also work, because readthedocs supports (currently) custom domains + https 🎉 See https://docs.readthedocs.io/en/latest/custom_domains.html#custom-domain-ssl and also the working example https://docs.nlog-project.org

As far as I know you need to do the following steps:

  • the CNAME needs to be updated to readthedocs.io. (currently autofac.readthedocs.org.)
  • edit and re-save the setting in readthedocs
  • SSL should work in one hour

Can code snippets have syntax highlighting enabled?

I'm not sure if this is a bug with the Autofac docs, Read the Docs, Sphinx, pygments, etc., or config setting, but it'd be nice if the C# code samples had syntax highlighting enabled.

It's all showing up as black in Chrome and Edge for me: screenshot.

I know Sphinx's markup docs states that sourcecode is an alias for the code-block directive, but perhaps switching from .. sourcecode:: csharp to .. code-block:: csharp might bring syntax highlighting back?

AutofacChildLifetimeScopeServiceProviderFactory setup documentation is invalid.

Incorrect documentation page:
https://autofaccn.readthedocs.io/en/latest/integration/aspnetcore.html#using-a-child-scope-as-a-root

The documentation explicitly showing how to setup the AutofacChildLifetimeScopeServiceProviderFactory where it takes 0 constructor arguments is incorrect.

    var host = Host.CreateDefaultBuilder(args)
        .UseServiceProviderFactory(new AutofacChildLifetimeScopeServiceProviderFactory())
        .ConfigureWebHostDefaults(webHostBuilder => {

As of Autofac.Extensions.DependencyInjection, Version=5.0.1.0 the AutofacChildLifetimeScopeServiceProviderFactory does not have any empty constructor.

https://github.com/autofac/Autofac.Extensions.DependencyInjection/blob/master/src/Autofac.Extensions.DependencyInjection/AutofacChildLifetimeScopeServiceProviderFactory.cs

autofac wcf instance managemenr

Hi,

This is not an issue. I want to understand how autofac handles instance management. I have a WCF service which is registered with its interface (Service contract).
Like.
container.RegisterType().As();
How it will manage instance? Will it create instance per call or per session or singleton.?
How it will manage concurrency? Will it be Single or multiple ?

What is default behaviour of autofac wcf package for this type of registration?

Thanks,
Ajay

Update API docs for v6

We need to run the API documentation generation process and update that documentation with the 6.0.0 APIs after everything is published. It does require the NuGet packages be published so the API doc rendering project can consume them all and generate linked docs.

Docs for working with plugins/dynamic assembly loading

Autofac isn't responsible for loading assemblies, that's the framework's responsibility. However, because folks wire up their plugins using a DI framework it's a common misconception that when an assembly fails to load or isn't found that it's an Autofac problem.

We need some docs that explain a few things:

  • Clarify that assembly loading isn't an Autofac concern.
  • Point out the example we have for simple .NET Core handling (which is not a recommendation, just a quick example).
  • Point out the docs on ASP.NET MVC Classic plugin assemblies as well as the IIS Restart problem
  • Note that there are a lot of considerations in designing a plugin framework and how none of these are built into Autofac:
    • Application type - different apps need different plugin mechanisms
    • Assembly location - how plugin assemblies get found
    • Plugin dependencies - how dependencies for plugins get resolved, particularly if they conflict
    • Security - potential need for loading assemblies in a safe context prior to loading them completely
    • Framework differences - .NET desktop might load everything in the bin folder automatically for a console app, but that isn't the same as how .NET desktop handles IIS apps (i.e., BuildManager and referenced assemblies), and that's not the same as how .NET Core locates and loads assemblies

Likely this is an FAQ sort of doc since it's not something we support (i.e., "Advanced Topics") and it's not application-specific.

Wrong location for Build instructions

And the bottom of this file there is following text:

Build instructions are in a README in the root of the code, and more information about the project is in the Contributor Guide

This is wrong, there is no instructions in a README in the root of the code, they are all in the Contributor Guide.

Verify ExtensibleActionInvoker example is correct

The example code on the MVC page explaining how to get parameter injection working shows only the call to RegisterActionInvoker but I think you also need to register the type ExtensibleActionInvoker. Check that, and add a bit about how you can use that to register your own custom invoker, too.

How to register with ASP.NET Core when not using UseStartup()?

The ASP.NET Core integration at https://github.com/autofac/Documentation/blob/v4.0.0/docs/integration/aspnetcore.rst assumes that the Startup class is used (via .UseStartup<T>). However, this is not necessarily the case - ASP.NET Core can be used without the Startup class.

How is one meant to hook up Autofac in such a situation? The regular IWebHostBuilder.ConfigureServices() method does not have an overload that can return AutofacServiceProvider.

Service resolution algorithm should be documented

Problem Statement

The documentation section on "Controlling Scope and Lifetime" refers to Nicholas Blumhardt's article. Therein one can find the following sentence "When the resolve operation has moved from a child scope to the parent, any further dependencies will be resolved in the parent scope."

This sentence made me believe that the following test would fail, i.e., I expected that resolving ComponentUser from innerScope would return ScopedComponent named "OUTER" because the resolution had resolve ComponentUser from the parent scope, where it was registered.

        [Fact]
        public void OuterComponentResolvesInnermostInstance() {
            var cb = new ContainerBuilder();

            var outerscoped = new ScopedComponent("OUTER");
            cb.RegisterInstance(outerscoped);
            cb.RegisterType(typeof(ComponentUser));

            using var outer = cb.Build();

            {
                var cu = outer.Resolve<ComponentUser>();
                Assert.Equal("OUTER", cu.SC.Name);
                Assert.True(ReferenceEquals(outerscoped, cu.SC));
            }

            {
                var innerscoped = new ScopedComponent("INNER");
                using var inner = outer.BeginLifetimeScope("InnerScope", cb2 => {
                    cb2.RegisterInstance(innerscoped);
                });
                
                var cu = inner.Resolve<ComponentUser>();
                Assert.Equal("INNER", cu.SC.Name);
                Assert.True(ReferenceEquals(cu.SC, innerscoped));

                var innerscoped2 = new ScopedComponent("INNER2");
                using (var inner2 = inner.BeginLifetimeScope("InnerScope2", cb2 => {
                    cb2.RegisterInstance(innerscoped2);
                })) {
                    var cu2 = inner2.Resolve<ComponentUser>();
                    Assert.Equal("INNER2", cu2.SC.Name);
                    Assert.True(ReferenceEquals(cu2.SC, innerscoped2));
                }

                var cu1 = inner.Resolve<ComponentUser>();
                Assert.Equal("INNER", cu.SC.Name);
                Assert.True(ReferenceEquals(cu1.SC, innerscoped));
            }

            {
                var cu = outer.Resolve<ComponentUser>();
                Assert.Equal("OUTER", cu.SC.Name);
                Assert.True(ReferenceEquals(outerscoped, cu.SC));
            }
        }

        class ScopedComponent
        {
            public readonly string Name;
            public ScopedComponent(string name) { Name = name; }
        }

        class ComponentUser
        {
            public ScopedComponent SC;
            public ComponentUser(ScopedComponent sc) { SC = sc; }
        }
    }

However, the test passes (actually the desired behavior).

Desired Solution

Documentation should contain an algorithmic description of the resolution process. The way things are now, I have no idea whether the above works by accident (by way of being an implementation detail) or by design.

Clarify which properties are auto-wired

Problem Statement

The PropertiesAutowired docs explain that properties get injected but not explicitly which properties (e.g., public, unset).

Desired Solution

Additional docs that spell out more explicitly which properties get injected.

It might be good to also add info about InjectUnsetProperties at the same time. Doesn't appear we have docs on that.

Clarify delegate factory docs with more commentary

I've been working on Autofac for years and still get confused on the whole delegate factory thing - how they work, why you'd do that over Func<X, Y, B>, and so on. I recently answered a StackOverflow question with a more detailed explanation of things in the docs like what "matches by name rather than type" really means. I think we should flesh out the delegate factory docs a bit more to make the feature more usable.

4.2 Implicit RelationshipTypes - KeyedServiceLookup

I was reading the documentation on your website and noticed something confusing.

In the sample code for the usage of IIndex<X, B> there seems to be a typo but I just want to make sure I'm not missing the point.

 public class A
 {
   IIndex<string, B> _b;

   public A(IIndex<string, B> b) { _b = b; }

   public void M()
   {
     var b = this._b["first"];
     **_b.DoSomething();**
   }
 }

The last line, "_b.DoSomething()", shouldn't that be b.DoSomething (without the underscore)

Clarify that AutoActivate() changes registered type

It came as a surprise to me that using .AutoActivate() means only IStartable will be registered, unless you also specify .As<>(), .AsSelf() or whatever.

Combined with AnyConcreteTypeNotAlreadyRegisteredSource (like in Prism), this can lead to apparent .SingleInstance() violations, if you just slap on .AutoActivate().

I feel the documentation should make it very clear that .AutoActive() changes the registered type. The name doesn’t really imply that.

(I may provide a pull request myself later.)

Update docs to include RegisterAssemblyOpenGenericTypes

Problem Statement

It isn't necessarily clear that RegisterAssemblyTypes should not be used to register open generics. We have a new RegisterAssemblyOpenGenericTypes mechanism for this and we'll need to have docs created for that.

Desired Solution

Update the docs on assembly scanning to indicate how to work with open generics.

It would be nice to have an example of the uniqueness of Instance Per Lifetime Scope in nested scope

In addition to the 2 samples provided, I think it would be nice/important to have one about the bolded sentence

A component with per-lifetime scope will have at most a single instance per nested lifetime scope

using(var scope3 = container.BeginLifetimeScope())
{
    var w3 = scope3.Resolve<Worker>();
    using(var scope4 = scope3.BeginLifetimeScope())
    {
        var w4 = scope4.Resolve<Worker>(); //w3 and w4 are 2 different instances
    }
}

I know the sentence sounds ok but I was in the impression that child scope were using parent scope instances and having an example would have cleared things out.

Autofac Not Intercepting

I cannot get autofac to intercept. I have the following setup in my .net core application:

// ************************************************
// Logger created:
// ************************************************

public class Logger : IInterceptor
{
    public void Intercept(IInvocation invocation)
    {
        // Logging removed for now
        var watch = System.Diagnostics.Stopwatch.StartNew();  // Added break point here
        invocation.Proceed(); 
        watch.Stop();
        var executionTime = watch.ElapsedMilliseconds;
    }
}

// ************************************************
// Class Created:
// ************************************************

[Intercept(typeof(Logger))]
public class ServiceProxy: ServiceInterface
{
    public User GetUser(String username, String password)
    {
        var service = ServiceHelper.GetODataClaimService();
        var query = from a in service.Users
                            select a;
        var dsq = query.ToDataServiceQuery<User>();
        var result = dsq.ToListSync<User>();
        var user = result.FirstOrDefault();
        return user;
    }
}

// ************************************************
// Interface Created:
// ************************************************

public interface ServiceInterface
{
    User GetUser(String username, String password);
}

// ************************************************
// Interception Configuration
// ************************************************

public class Interceptor
{
    public static void Configure()
    {
        var builder = new ContainerBuilder();
        builder.Register(a => new Logger());
        builder.RegisterType<ServiceProxy>().As<ServiceInterface>().EnableInterfaceInterceptors().InterceptedBy(typeof(Logger));  // Tried removing intercepted by
        var container = builder.Build();
        var worker = container.Resolve<ServiceInterface>();
        builder.Build()
    }
}

I put a break point in the logger to see if it ever enters that block of code.
It never does. What am I missing here?
I've tried quite a few configurations but nothing seems to work.
Also - The Configure method is invoked from application Startup..

Please advise.

Break down .NET Core / ASP.NET Core docs

Since ASP.NET Core first came out, there's a lot that has changed. It would probably be good to reorganize the documentation around .NET Core things. There's a lot to discuss:

  • .NET Core - basic usage of the AutofacServiceProvider when not used in any sort of hosted app. Think console app or something that doesn't have the hosting bits wrapped up in it.
  • .NET Core generic hosting - new in .NET Core 3, this creates a concept of generic app startup for an application. Affects how ASP.NET Core handles app hosting.
  • ASP.NET Core - in .NET Core 1.0 - 2.2 this is all about web hosting; in .NET Core 3.0 it's an add-on for generic hosting. There are also things like controllers-as-services, differences between .NET Core and .NET Desktop (WebAPI, MVC), that sort of thing. Even just in this topic there's a lot to break down.
  • Blazor - Similar to ASP.NET Core in that it uses a hosting model but may need to have some information about dealing with optimization (e.g., how the Xamarin and .NET Native linkers filter out types they see as unused... does Blazor do that?)
  • Multitenant support - we have a multitenant service provider factory. Need to keep examples for that stuff.

This isn't a suggestion that each of these topics get the pages I just listed. That's probably not the right granularity. For example, it may be better to put multitenant notes on specific pages with examples rather than on its own page. Or maybe the .NET Core and generic hosting stuff all go on one page. Part of the task here is to come up with a good breakdown/structure for this that can be extended as time goes on and new app types arise.

Clarify how lifetime scopes relate to dependency resolution

Based on autofac/Autofac#1046 - The documentation explains how to avoid captive dependencies, but there's a concept that hasn't been fully explained, which is how a given component locates dependencies.

For example, if you resolve a singleton, even if it's being resolved from a child lifetime scope, the singleton comes from the root container.

If you have a child lifetime scope where an instance-per-dependency component depends on a singleton, the singleton comes from the root but the instance-per-dependency comes from the child scope.

How do things like instance-per-lifetime-scope interact with various components? If you have a singleton that takes in a Func<T> dependency, which lifetime scope is it tied to? We don't really spell these sorts of things out in a clear way, so questions pop up fairly frequently that wonder why singletons aren't somehow getting scoped values injected.

Populate method missing with latest version

Hello,
I just installed the Autofac package in my dotnet standard class library 2.2;
the following statement doesn't work anymore

builder.Populate(services);

Populate method looks like is missing
When I decompile the assembly, I can't find the method anymore:

2019-02-04_16h22_07

Did you change the interface ?
Txs in advance
-v

log4net example only works with Constructor Injection

https://github.com/autofac/Documentation/blob/master/docs/examples/log4net.rst

This code doesn't work if you have a component that uses a Service Locator design pattern (Resolve<T>), like the following PowerShell cmdlet (PowerShell does not allow calling non-default constructors, and currently does not support Microsoft.Extensions.DependencyInjection):

public class SuperPingCommand : Cmdlet
{
  private ILog _log;
  SuperPingCommand()
  {
     // OnComponentPreparing will have e.Parameters.Count == 0 at time of method entry.
     // The example code leads to no customization of the ILog object constructor.
     // Because of this, there is no nice IoC way to configure semantic logging in PowerShell
    _log = Resolve<ILog>();
  }
}

Potential opportunity to simplify Startup.cs config in docs' Application Integration's ASP.NET Core 3.x section

Problem Statement

It may be possible to reduce the Startup.cs config at https://autofaccn.readthedocs.io/en/latest/integration/aspnetcore.html#startup-class.

Here's the current Startup constructor from the link above:

public Startup(IHostingEnvironment env)
  {
    // In ASP.NET Core 3.0 `env` will be an IWebHostEnvironment, not IHostingEnvironment.
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
        .AddEnvironmentVariables();
    this.Configuration = builder.Build();
  }

According to the Host.CreateDefaultBuilder documentation, the stuff in the Startup's constructor is done for you when using Host.CreateDefaultBuilder (which the Autofac docs do in the suggested Program.cs file).

Desired Solution

Here's what the full Startup class for ASP.NET Core 3.x could look like after removing the redundant config. Changes have been denoted with "// UPDATED".

public class Startup
{

  // UPDATED constructor's contents and parameter
  public Startup(IConfiguration configuration)
  {
    this.Configuration = configuration;
  }

  public IConfiguration Configuration { get; private set; } // UPDATED type from IConfigurationRoot to IConfiguration

  public ILifetimeScope AutofacContainer { get; private set; }

  // ConfigureServices is where you register dependencies. This gets
  // called by the runtime before the ConfigureContainer method, below.
  public void ConfigureServices(IServiceCollection services)
  {
    // Add services to the collection. Don't build or return
    // any IServiceProvider or the ConfigureContainer method
    // won't get called. Don't create a ContainerBuilder
    // for Autofac here, and don't call builder.Populate() - that
    // happens in the AutofacServiceProviderFactory for you.
    services.AddOptions();
  }

  // ConfigureContainer is where you can register things directly
  // with Autofac. This runs after ConfigureServices so the things
  // here will override registrations made in ConfigureServices.
  // Don't build the container; that gets done for you by the factory.
  public void ConfigureContainer(ContainerBuilder builder)
  {
    // Register your own things directly with Autofac here. Don't
    // call builder.Populate(), that happens in AutofacServiceProviderFactory
    // for you.
    builder.RegisterModule(new MyApplicationModule());
  }

  // Configure is where you add middleware. This is called after
  // ConfigureContainer. You can use IApplicationBuilder.ApplicationServices
  // here if you need to resolve things from the container.
  public void Configure(
    IApplicationBuilder app,
    ILoggerFactory loggerFactory)
  {
    // If, for some reason, you need a reference to the built container, you
    // can use the convenience extension method GetAutofacRoot.
    this.AutofacContainer = app.ApplicationServices.GetAutofacRoot();

    loggerFactory.AddConsole(this.Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();
    app.UseMvc();
  }
}

Incorrect usage of Owned<> in per-request scope example

Describe the Bug

In the documentation there is a per-request scope sample: https://autofaccn.readthedocs.io/en/latest/integration/servicefabric.html#per-request-scopes

In the following snippet, the using statement is taking on the Value of the Owned instance.

private readonly Func<Owned<IUserStore>> _userStoreFactory;

public async Task<string> GetNameAsync(int id)
{
  using (var userStore = _userStoreFactory().Value)
  {
    return await userStore.GetNameAsync(id);
  }
}

Steps to Reproduce

The following program demonstrates that disposing the Owned.Value will not dispose the lifetime scope:

class DbContext : IDisposable
{
    public void Dispose()
    {
        Console.WriteLine("DbContext disposed");
    }
}

class Repository : IDisposable
{
    private readonly DbContext _dbContext;

    public Repository(DbContext dbContext)
    {
        _dbContext = dbContext;
    }

    public void Dispose()
    {
        Console.WriteLine("Repository disposed");
    }
}
        
static void Main(string[] args)
{
    var builder = new ContainerBuilder();
    builder.RegisterType<DbContext>().InstancePerDependency();
    builder.RegisterType<Repository>().InstancePerDependency();
    var container = builder.Build();

    var repositoryFactory = container.Resolve<Func<Owned<Repository>>>();
    using (var repository = repositoryFactory())
    {
        Console.WriteLine("Test autofac/Autofac.ServiceFabric#1: disposal of Owned");
    }

    Console.WriteLine();

    using (var repository = repositoryFactory().Value)
    {
        Console.WriteLine("Test autofac/Autofac.ServiceFabric#2: disposal of Owned.Value");
    }
}

Expected Behavior

Replace

    using (var userStore = _userStoreFactory().Value)
    {
      return await userStore.GetNameAsync(id);
    }

with

    using (var userStore = _userStoreFactory())
    {
      return await userStore.Value.GetNameAsync(id);
    }

Documentation of Implicit Relationships isn't quite clear

I was recently trying to work out how Func and Func<X,Y,T> bindings should be used, and the documentation of how it should be used at the point of declaring and using the dependency is great! But I think there are 2 steps of the documentation missing:

  1. Examples of How you declare and register your dependency (in particular the fact that it's keying off the constructor params and registration is not any different; you don't need to register a lamda, for example)

  2. Notes on how Func<??, T> dependencies work when the dependency has other, NON parameterised dependencies (i.e. the fact that Autofac will fill them in for us.)

I'm happy (nay, keen) to try to write those changes to the docs, but want to check that they'd be welcome before doing so.

LMK if you're happy to receive a PR for updates.

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.