Is Autofac magical?


The answer is yes!

OK let me explain. I never registered anything as Func<IObservable<object>> and yet the below code still works. It turns out to be that not only does autofac understand Func<Dependency>(), it understands a whole bunch of things that you may or may not have intended to be dependency relationships. 🙂

The details [Copied straight from http://autofac.readthedocs.org/en/latest/resolve/relationships.html]

B Direct Dependency
A needs B at some point in the future Lazy<B> Delayed Instantiation
A needs B until some point in the future Owned<B> Controlled Lifetime
A needs to create instances of B Func<B> Dynamic Instantiation
A provides parameters of types X and Y to B Func<X,Y,B> Parameterized Instantiation
A needs all the kinds of B IEnumerable<B>, IList<B>, ICollection<B> Enumeration
A needs to know X about B Meta<B> and Meta<B,X> Metadata Interrogation
A needs to choose B based on X IIndex<X,B>

So now I know!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Autofac;

namespace IsAutoFacMagical
{
    class CO : IObservable<object>
    {
        public IDisposable Subscribe(IObserver<object> observer)
        {
            throw new NotImplementedException();
        }
    }

    class DO
    {
        public Func<IObservable<object>> Magic { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var cb = new ContainerBuilder();
            cb.RegisterType<CO>().As<IObservable<object>>();
            cb.RegisterType<DO>().PropertiesAutowired();
            var x = cb.Build();
            var d = x.Resolve<DO>();
            var m1 = d.Magic();
        }
    }
}

Comments (0)

Skip to main content