IoC wraps Autofac for using dynamic services
Last active
April 17, 2017 18:53
-
-
Save pmunin/e21efce57f2e7d0b758f5282841f71d8 to your computer and use it in GitHub Desktop.
Services Utils - automatic registration using AutoFac as dependency
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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