Skip to content

Instantly share code, notes, and snippets.

@pmunin
Last active April 17, 2017 18:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pmunin/e21efce57f2e7d0b758f5282841f71d8 to your computer and use it in GitHub Desktop.
Save pmunin/e21efce57f2e7d0b758f5282841f71d8 to your computer and use it in GitHub Desktop.
Services Utils - automatic registration using AutoFac as dependency

IoC wraps Autofac for using dynamic services

using System;
using System.Collections.Generic;
using System.Text;
namespace ServicesUtils
{
public interface IServiceProvider
{
T Get<T>(object key=null) where T:class;
IEnumerable<T> GetAll<T>() where T:class;
}
}
using Autofac;
using System;
using System.Linq;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
namespace ServicesUtils
{
public partial class Services : IServiceProvider
{
public static IServiceProvider Current { get; } = new Services();
T IServiceProvider.Get<T>(object key)
{
if (key == null)
return Container.ResolveOptional<T>();
else
return Container.ResolveOptionalKeyed<T>(key);
}
public static T Get<T>(object key = null) where T : class
{
return ((IServiceProvider)Current).Get<T>(key);
}
public static IEnumerable<T> GetAll<T>() where T : class
{
return ((IServiceProvider)Current).GetAll<T>();
}
IEnumerable<T> IServiceProvider.GetAll<T>()
{
return Container.Resolve<IEnumerable<T>>();
}
private static IContainer Container { get; set; }
public static void Configure(Action<ContainerBuilder> config)
{
var builder = new ContainerBuilder();
config(builder);
if (Container == null)
Container = builder.Build();
else
#pragma warning disable CS0618 // Type or member is obsolete
builder.Update(Container);
#pragma warning restore CS0618 // Type or member is obsolete
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment