We're trying to create a delivery recipe based on HotTowel Angular + Breeze. The dependency injection part in the SPA app is well covered but trying to resolve the BreezeController through Unity proves to be a challenge. I may lack one thing in there but haven't figured it out.
So far here's what we've done:
Unity bootstrapper for ASP.NET MVC 3.5.1404 is installed
Added a new controller called LoggingController which applies the BreezeController attribute
On this controller set a repository dependency through the constructor
All's good and clean, Unity container is activated through UnityMvcActivator.cs which looks like this:
using System.Linq;
using System.Web.Mvc;
using Microsoft.Practices.Unity.Mvc;
[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(CC.Web.App_Start.UnityWebActivator), "Start")]
[assembly: WebActivatorEx.ApplicationShutdownMethod(typeof(CC.Web.App_Start.UnityWebActivator), "Shutdown")]
namespace CC.Web.App_Start
{
/// <summary>Provides the bootstrapping for integrating Unity with ASP.NET MVC.</summary>
public static class UnityWebActivator
{
/// <summary>Integrates Unity when the application starts.</summary>
public static void Start()
{
var container = UnityConfig.GetConfiguredContainer();
FilterProviders.Providers.Remove(FilterProviders.Providers.OfType<FilterAttributeFilterProvider>().First());
FilterProviders.Providers.Add(new UnityFilterAttributeFilterProvider(container));
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
// TODO: Uncomment if you want to use PerRequestLifetimeManager
Microsoft.Web.Infrastructure.DynamicModuleHelper.DynamicModuleUtility.RegisterModule (typeof(UnityPerRequestHttpModule));
}
/// <summary>Disposes the Unity container when the application is shut down.</summary>
public static void Shutdown()
{
var container = UnityConfig.GetConfiguredContainer();
container.Dispose();
}
}
}
The container is configured through UnityConfig.cs
using System;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;
using System.Web.Mvc;
using Microsoft.Practices.Unity.Mvc;
using System.Web.Http;
namespace CC.Web.App_Start
{
/// <summary>
/// Specifies the Unity configuration for the main container.
/// </summary>
public class UnityConfig
{
#region Unity Container
private static Lazy<IUnityContainer> container = new Lazy<IUnityContainer>(() =>
{
var container = new UnityContainer();
RegisterTypes(container);
return container;
});
/// <summary>
/// Gets the configured Unity container.
/// </summary>
public static IUnityContainer GetConfiguredContainer()
{
return container.Value;
}
#endregion
/// <summary>Registers the type mappings with the Unity container.</summary>
/// <param name="container">The unity container to configure.</param>
/// <remarks>There is no need to register concrete types such as controllers or API controllers (unless you want to
/// change the defaults), as Unity allows resolving a concrete type even if it was not previously registered.</remarks>
public static void RegisterTypes(IUnityContainer container)
{
// NOTE: To load from web.config uncomment the line below. Make sure to add a Microsoft.Practices.Unity.Configuration to the using statements.
container.LoadConfiguration();
// TODO: Register your types here
// container.RegisterType<IProductRepository, ProductRepository>();
}
}
}
Upon calling the controller it seems Unity is not in charge as it throws an error about not finding an empty constructor.
I would assume DependencyResolver.SetResolver(new UnityDependencyResolver(container)); would properly tell which resolver to use like in Mike Wasson blog post mentionned by Steve: config.DependencyResolver = new UnityResolver(container);. UnityDependencyResolver does implement IDependencyResolver.
So what I'm asking, assuming that installing the Nuget Package is only what is needed to hook Unity as a resolver, is there a way to use Unity as a Resolver for Breeze controllers or should we simply use the Breeze controllers as facade to a properly IOC built component? I'd rather have the resolving done through Unity transparently instead of going through a facade.
You will want the Unity.AspNet.WebApi package for resolving WebApi controllers (including Breeze controllers).
You also need to tell WebApi to use Unity to resolve dependencies. Usually this is done in some static method that you call from Global.asax.cs. This blog post by Mike Wasson lays it all out.
The Unity.WebAPI Github page suggests using the UnityConfig.RegisterComponents()method for registering your repositories.
Related
I am facing problem with disposing unnecessary objects from DI container. I use Prism for Xamarin.Forms with Unity container.
Application gets configuration from some database, creates some services using this configuration and registers this services in container using ContainerControlledLifetimeManager. This services are used while resolving views and viewmodels.
When configuration changes application retrieves again changed configuration and now problem comes: how can I remove previous registrations and register new services? If I simply re-register service then previous service is not GC-ed until disposing container.
I cannot dispose container, because it is created and managed by Prism (can I?).
I cannot use child container because Prism will not resolve views and viewmodels using child container (can I?)
Should I use different DI? Does Autofac or other DI support such approach?
EDIT:
I just have tested disposing of re-registered objects in Unity. It came out that re-registering using:
Container.RegisterType<IFoo, Foo>(new ContainerControlledLifetimeManager())
really releases previously registered objects. But I have also registrations using just type:
Container.RegisterType<Foo>(new ContainerControlledLifetimeManager())
or using instance:
Container.RegisterInstance(new Foo())
and these objects are not released when re-registering.
So now the only solution is to reconstruct the Unity container? Or give a try to other ioc container?
Without knowing all of the specifics of what you are looking to accomplish it's impossible to give you a solid roadmap, so I'll touch on some things to consider.
Reregistering Services
If you have some service IFoo, and two implementations FooA and FooB and you initially registered FooA as the implementation for IFoo (with a container controlled lifetime, registering FooB with the container should dispose of the FooA instance and FooB should be generated going forward.
Reconstructing the container
If you have to reconstruct the Container, it should possible. I haven't ever run into a use case where I have had to try something like what you are looking to do. For starters you probably want to take a look at the Initialize method from PrismApplicationBase. This is where the container gets constructed and setup. To handle the reconstruction, you will want to create an event that you subscribe to in your App class.
public partial class App
{
protected override void OnInitialized()
{
var ea = Container.Resolve<IEventAggregator>();
ea.GetEvent<SettingsChangedEvent>().Subscribe(OnSettingsChangedEvent);
// navigate
}
private void OnSettingsChangedEvent()
{
var ea = Container.Resolve<IEventAggregator>();
// prevent a memory leak
ea.GetEvent<SettingsChangedEvent>().Unsubscribe(OnSettingsChangedEvent);
// If you need platform specific types be sure to register either the
// IPlatformInitializer or some similar helper
var platformInitializer = Container.Resolve<IPlatformInitializer>();
ModuleCatalog = CreateModuleCatalog();
ConfigureModuleCatalog();
Container = CreateContainer();
ConfigureContainer();
// This would be your original RegisterTypes, so this assumes you
// look at your settings when initially registering types.
RegisterTypes();
// See notes above
platformInitializer.RegisterTypes(Container);
NavigationService = CreateNavigationService();
InitializeModules();
// Your container is now reset.
var ea = Container.Resolve<IEventAggregator>();
ea.GetEvent<SettingsChangedEvent>().Subscribe(OnSettingsChangedEvent>()
}
}
Containers
As for choosing a container. There is nothing wrong with Unity. Just know that when you're working with Unity, you're going to be stuck with the way it is since it apparently it is a dead project now. Ninject for Prism Forms uses a PCL variant that doesn't seem to be maintained anymore, but when the switch to NetStandard is made Prism will be able to target the current version of Ninject. As for Autofac, there you are dealing with an immutable container so the moment you resolve something you cannot update any new registrations. Autofac for Prism Forms is also a version behind for the same reason as Ninject. DryIoc for Prism forms is a great container and actually the one I am using on all of my current projects. It is also being actively maintained so you can expect use cases you run into to at least be heard.
Thanks for help to Dan S. and R. Richards.
Recreating Prism container caused problems in navigation. Maybe it is possible to fix it but I do not know how.
Using different IOC container would require too much time to learn it.
I ended up with custom lifetime manager (the solution provided in R. Richards link):
class CustomLifetimeManager : LifetimeManager
{
private object _Value;
public override object GetValue()
{
return _Value;
}
public override void RemoveValue()
{
_Value = null;
}
public override void SetValue(object newValue)
{
_Value = newValue;
}
}
Above lifetime manager allows to remove registrations:
public static class UnityContainerExtension
{
/// <summary>
/// Removes registrations that were registred using <see cref="CustomLifetimeManager"/>
/// </summary>
/// <param name="container"></param>
public static void RemoveCustomLifetimeRegistrations(this IUnityContainer container)
{
var registrations = container.Registrations.Where(r => r.LifetimeManagerType == typeof(CustomLifetimeManager));
foreach(var r in registrations)
{
r.LifetimeManager.RemoveValue();
}
}
}
Update 09.08.2018
Unity is being developed here but I haven't had the time to test how it plays with the ASP.NET Core framework.
Update 15.03.2018
This solution is for the specific problem of using ASP.NET Core v1 with Unity while using the .NET Framework 4.5.2 NOT the .NET Core Framework. I had to use this setup since I needed some .Net 4.5.2 DLLs but for anyone starting afresh I would not recommend this approach. Also Unity is not being developed any further (to my knowlage) so I would recommend using the Autofac Framework for new projects. See this Post for more info on how to do that.
Intro
I am building a Web Application using ASP.NET with MVC. This Application depends on certain services (a WCF Service a Datastore service etc). Now to keep things nice and decoupled I want to use a DI (Dependecy Injection) Framework, specifically Unity.
Initial Research
I found this blog post but sadly its not working. The idea though is nice. It basically says that you should not register all the services registered in the ServiceCollection into your own container, but rather reference the default ServiceProvider. So. if something needs to be resolved the default ServiceProvider is called and in case it has no resolution the type will be resolved using your custom UnityContainer.
The Problems
MVC always tries to resolve the Controller with the default ServiceProvider. Also, I noticed that even if the Controller would get resolved correctly, I can never "mix" Dependencies. Now, if I want to use one of my Services but also an IOptions interface from ASP the class can never be resolved because not one of those two containers has resolutions for both types.
What I need
So to recap I need the following things:
A setup where I dont need to copy ASP.NET Dependencies into my UnityContainer
A container which can resolve my MVC Controllers
A container which can resolve "mixed" Dependencies
EDIT:
So the question is how can I achieve these points ?
Environment
project.json:
So after some research I came up with the following solutions to my problems:
Use Unity with ASP
To be able to use Unity with ASP I needed a custom IServiceProvider (ASP Documentation) so I wrote a wrapper for the IUnityContainer which looks like this
public class UnityServiceProvider : IServiceProvider
{
private IUnityContainer _container;
public IUnityContainer UnityContainer => _container;
public UnityServiceProvider()
{
_container = new UnityContainer();
}
#region Implementation of IServiceProvider
/// <summary>Gets the service object of the specified type.</summary>
/// <returns>A service object of type <paramref name="serviceType" />.-or- null if there is no service object of type <paramref name="serviceType" />.</returns>
/// <param name="serviceType">An object that specifies the type of service object to get. </param>
public object GetService(Type serviceType)
{
//Delegates the GetService to the Containers Resolve method
return _container.Resolve(serviceType);
}
#endregion
}
Also I had to change the Signature of the ConfigureServices method in my Startup class from this:
public void ConfigureServices(IServiceCollection services)
to this:
public IServiceProvider ConfigureServices(IServiceCollection services)
Now I can return my custom IServiceProvider and it will be used instead of the default one.The full ConfigureServices Method is shown in the Wire up section at the bottom.
Resolving Controllers
I found this blog post. From it I learned that MVC uses an IControllerActivator interface to handle Controller instantiation. So I wrote my own which looks like this:
public class UnityControllerActivator : IControllerActivator
{
private IUnityContainer _unityContainer;
public UnityControllerActivator(IUnityContainer container)
{
_unityContainer = container;
}
#region Implementation of IControllerActivator
public object Create(ControllerContext context)
{
return _unityContainer.Resolve(context.ActionDescriptor.ControllerTypeInfo.AsType());
}
public void Release(ControllerContext context, object controller)
{
//ignored
}
#endregion
}
Now if a Controller class is activated it will be instatiated with my UnityContainer. Therefore my UnityContainer must know how to Resolve any Controller!
Next Problem: Use the default IServiceProvider
Now if I register services such as Mvc in ASP.NET I normally would do it like this:
services.AddMvc();
Now if I use a UnityContainer all the MVC Dependencies could not be Resolved because they aren't Registered. So I can either Register them (like AutoFac) or I can create a UnityContainerExtension. I opted for the Extension and came up with following two clases :
UnityFallbackProviderExtension
public class UnityFallbackProviderExtension : UnityContainerExtension
{
#region Const
///Used for Resolving the Default Container inside the UnityFallbackProviderStrategy class
public const string FALLBACK_PROVIDER_NAME = "UnityFallbackProvider";
#endregion
#region Vars
// The default Service Provider so I can Register it to the IUnityContainer
private IServiceProvider _defaultServiceProvider;
#endregion
#region Constructors
/// <summary>
/// Creates a new instance of the UnityFallbackProviderExtension class
/// </summary>
/// <param name="defaultServiceProvider">The default Provider used to fall back to</param>
public UnityFallbackProviderExtension(IServiceProvider defaultServiceProvider)
{
_defaultServiceProvider = defaultServiceProvider;
}
#endregion
#region Overrides of UnityContainerExtension
/// <summary>
/// Initializes the container with this extension's functionality.
/// </summary>
/// <remarks>
/// When overridden in a derived class, this method will modify the given
/// <see cref="T:Microsoft.Practices.Unity.ExtensionContext" /> by adding strategies, policies, etc. to
/// install it's functions into the container.</remarks>
protected override void Initialize()
{
// Register the default IServiceProvider with a name.
// Now the UnityFallbackProviderStrategy can Resolve the default Provider if needed
Context.Container.RegisterInstance(FALLBACK_PROVIDER_NAME, _defaultServiceProvider);
// Create the UnityFallbackProviderStrategy with our UnityContainer
var strategy = new UnityFallbackProviderStrategy(Context.Container);
// Adding the UnityFallbackProviderStrategy to be executed with the PreCreation LifeCycleHook
// PreCreation because if it isnt registerd with the IUnityContainer there will be an Exception
// Now if the IUnityContainer "magically" gets a Instance of a Type it will accept it and move on
Context.Strategies.Add(strategy, UnityBuildStage.PreCreation);
}
#endregion
}
UnityFallbackProviderStrategy:
public class UnityFallbackProviderStrategy : BuilderStrategy
{
private IUnityContainer _container;
public UnityFallbackProviderStrategy(IUnityContainer container)
{
_container = container;
}
#region Overrides of BuilderStrategy
/// <summary>
/// Called during the chain of responsibility for a build operation. The
/// PreBuildUp method is called when the chain is being executed in the
/// forward direction.
/// </summary>
/// <param name="context">Context of the build operation.</param>
public override void PreBuildUp(IBuilderContext context)
{
NamedTypeBuildKey key = context.OriginalBuildKey;
// Checking if the Type we are resolving is registered with the Container
if (!_container.IsRegistered(key.Type))
{
// If not we first get our default IServiceProvider and then try to resolve the type with it
// Then we save the Type in the Existing Property of IBuilderContext to tell Unity
// that it doesnt need to resolve the Type
context.Existing = _container.Resolve<IServiceProvider>(UnityFallbackProviderExtension.FALLBACK_PROVIDER_NAME).GetService(key.Type);
}
// Otherwise we do the default stuff
base.PreBuildUp(context);
}
#endregion
}
Now if my UnityContainer has no Registration for something it just ask the default Provider for it.
I learned all of this from several different articles
MSDN Unity article
Auto-Mocking Unity Container Extension
Custom Object Factory Unity Extension
The nice thing about this approach is that I can also "mix" Dependencies now. If I need any of my Services AND an IOptions Interface from ASP my UnityContainer will resolve all of these Dependencies and Inject them into my Controller !!! The only thing to remember is that if I use any of my own Dependencies I have to register my Controller class with Unity because the default IServiceProvider can no longer Resolve my Controllers Dependencies.
Finally: Wire up
Now in my project I use different services (ASP Options, MVC with options). To make it all work my ConfigureServices Method looks like this now:
public IServiceProvider ConfigureServices(IServiceCollection services)
{
// Add all the ASP services here
// #region ASP
services.AddOptions();
services.Configure<WcfOptions>(Configuration.GetSection("wcfOptions"));
var globalAuthFilter = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
services.AddMvc(options => { options.Filters.Add(new AuthorizeFilter(globalAuthFilter)); })
.AddJsonOptions
(
options => options.SerializerSettings.ContractResolver = new DefaultContractResolver()
);
// #endregion ASP
// Creating the UnityServiceProvider
var unityServiceProvider = new UnityServiceProvider();
IUnityContainer container = unityServiceProvider.UnityContainer;
// Adding the Controller Activator
// Caution!!! Do this before you Build the ServiceProvider !!!
services.AddSingleton<IControllerActivator>(new UnityControllerActivator(container));
//Now build the Service Provider
var defaultProvider = services.BuildServiceProvider();
// Configure UnityContainer
// #region Unity
//Add the Fallback extension with the default provider
container.AddExtension(new UnityFallbackProviderExtension(defaultProvider));
// Register custom Types here
container.RegisterType<ITest, Test>();
container.RegisterType<HomeController>();
container.RegisterType<AuthController>();
// #endregion Unity
return unityServiceProvider;
}
Since I learned most of what I know about DI in the past week I hope I didnt break any big Pricipal/Pattern if so please tell me!
For ASP.Net Core 2.0, 2.1, 2.2, 3.1 and Unity there is official solution available from Unity authors as NuGet package here: NuGetPackage
Here is Git repository with samples: Git repo
Usage is very simple (from Git repo homepage):
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseUnityServiceProvider() <---- Add this line
.UseStartup<Startup>()
.Build();
And here is example with Unity DI for ASP.Net Core.
I am using this solution in my ASP.Net Core application and works good.
I'm working at a ASP.NET Webforms project and is using Unity for DI.
This project also use DevExpress ASP.NET Ajax Controls.
Now we have run into problem and it seems to be a conflict between DevExpress and Unity.
This is the Unity configuration
[assembly: WebActivator.PostApplicationStartMethod(typeof(Sales.Web.App_Start.UnityWebFormsStart), "PostStart")]
namespace Sales.Web.App_Start
{
/// <summary>
/// Startup class for the Unity.WebForms NuGet package.
/// </summary>
internal static class UnityWebFormsStart
{
/// <summary>
/// Initializes the unity container when the application starts up.
/// </summary>
/// <remarks>
/// Do not edit this method. Perform any modifications in the
/// <see cref="RegisterDependencies" /> method.
/// </remarks>
internal static void PostStart()
{
IUnityContainer container = new UnityContainer();
HttpContext.Current.Application.SetContainer(container);
RegisterDependencies(container);
}
/// <summary>
/// Registers dependencies in the supplied container.
/// </summary>
/// <param name="container">Instance of the container to populate.</param>
private static void RegisterDependencies(IUnityContainer container)
{
// TODO: Add any dependencies needed here
container
.RegisterType<IDbFactory, DbFactory>(new HierarchicalLifetimeManager())
.RegisterType(typeof(IDbProxy<>), typeof(DbProxy<>))
.RegisterType<IErpData, ErpData>(new HierarchicalLifetimeManager())
.RegisterType<ICaseData, CaseData>(new HierarchicalLifetimeManager())
.RegisterType<ICaseCauseData, CaseCauseData>(new HierarchicalLifetimeManager())
.RegisterType<ICaseHandler, CaseHandler>(new HierarchicalLifetimeManager());
}
}
}
Any of this Unity configuration has nothing to do with the DevExpress controls, but i think it hooks up the HttpContext object.
And this error appears only when i use the TabControl from DevExpress, all other controls works well.
See the attached image that describe the error message more in detail.
By convention, Unity prefers the constructor with the longest parameter list if no other configuration was supplied. Having two constructors with parameter list of equal length creates an ambiguity, so Unity throws an exception. That's why it cannot resolve the control you are using.
You can explicitly tell Unity which constructor to prefer:
container.RegisterType<IService, Service>(new InjectionConstructor(typeof(IServiceDependency)));
You can use the [InjectionConstructor] attribute on the contructor wanted
I have had the same problem adding this into my unityconifg resloved it
public static void RegisterTypes(IUnityContainer container)
{
container.UseApplicationLayer(false);
container.UseApplicationRepository(false);
container.ConfigureMappings();
}
using Nhiberante
I have an ApiController in an Area of my MVC website, I'm injecting dependencies into it via Unity and my controllers extend the System.Web.Http.ApiController.
I'm using Unity from Microsoft.Practices.Unity.dll, v3.0.0.0.
I can route to the controller with the following in ApiAreaRegistration
context.MapRoute(
"Api_default",
"Api/users/{action}/{id}"
);
But I get the following error :
Type 'Project.Areas.Api.Controllers.UsersController' does not have a default constructor
However if I add a default constructor my dependencies don't get resolved.
I'm beginning to feel like I'm missing something structural?
You don't show your controller registration and the error message suggests you have not registered the controller dependencies.
I use the Unity.WebAPI NuGet package to take care of the controller build-up and container lifetime management. If your project also uses MVC controllers the Unity.Mvc3 will handle those controllers. These packages get Unity wired-up for my controllers with very little code.
My Unity bootstrap looks like this
public static class UnityConfig
{
var container = BuildUnityContainer();
// MVC controllers
DependencyResolver.SetResolver(new Unity.Mvc3.UnityDependencyResolver(container));
// WebAPI controllers
GlobalConfiguration.Configuration.DependencyResolver = new Unity.WebApi.UnityDependencyResolver(container);
}
private static IUnityContainer BuildUnityContainer()
{
var container = new UnityContainer();
// register all your components with the container here
// you don't need to register controllers
container.RegisterType<IUsersService, UsersService>();
...
return container;
}
And I don't worry about my controller creation -- It just works.
public class UsersController : ApiController
{
private IUsersService service;
public UsersController(IUsersService service)
{
this.service = service;
}
...
}
GlobalConfiguration.Configuration.DependencyResolver =
new UnityDependencyResolver(YOUR_UNITY_CONTAINER);
and from http://msdn.microsoft.com/en-us/library/dn178463(v=pandp.30).aspx#sec18 you can find that you should search for 'Unity bootstrapper for ASP.NET WebApi' and you get the UnityDependencyResolver from the namespace: 'Microsoft.Practices.Unity.WebApi'.
Easiest way is just to install the WebApi Bootstrapper and look in the App_Start folder.
I would like to understand how i can resolve a unity named type registration within an MVC4 application.
I am using "Unity 3.0" and the "Unity boostrapper for ASP.NET MVC".
I understand that unity is registered with the DependencyResolver and so i can use the dependency resolver methods to get an instance of an registered type.
This works fine when I want to get a simple registration back.
e.g
//Registration
container.RegisterType<IFootballer, VanPersey>();
//Instantiation
var footballer1 = DependencyResolver.Current.GetService<IFootballer>();
But on an occasion when I want to get a reference to a named type registration it doesn't appear that the IDependencyResolver interface provides the appropriate methods to get named type registration instances.
If I had access to the unity container directly I would do something like the following:
//Registration
container.RegisterType<IFootballer, VanPersey>("Attacker" );
container.RegisterType<IFootballer, NemanjaVidic>("Defender");
//Instantiation
unityContainer.Resolve<IFootballer, Footballer>("Attacker")
So my question is , what is the most appropriate way to use unity in an MVC app in order to get an instance of a named registration. ie is there access to the unity comtainer?
Note that this question is not for any production implementation, I am looking at Unity (and IoC containers for the first time) and tying to get a better understanding.
I understand in production I would more than likely be passing in the dependencies through the controllers constructors, which actually leads me to another question.
How would it be possible to indicate which named type you wanted to resolve when using controller constructor injection in the following example:
//Registration
container.RegisterType<IFootballer, VanPersey>("Attacker" );
container.RegisterType<IFootballer, NemanjaVidic>("Defender");
//Instantiation
public HomeController(IFootballer footballer)
Most probably the container itself is also registered so that the resolver can resolve it:
var container = DependencyResolver.Current.GetService<IUnityContainer>();
var vanPersey = container.RegisterType<IFootballer, VanPersey>("Attacker" );
Haven't tried it with the resolver but it always worked like that with the ServiceLocator.
Incase this helps anyone else wanting to do the same thing, I found the following:
When using "Unity 3.0" and the "Unity boostrapper for AP.NET MVC" I found that un the UnityConfig class that it exposes a GetConfiguredContainer method in which you can directly access the unity container without having to use the dependency resolver.
Snippet from UnityConfig
/// <summary>
/// Specifies the Unity configuration for the main container.
/// </summary>
public class UnityConfig
{
#region Unity Container
private static Lazy<IUnityContainer> container = new Lazy<IUnityContainer>(() =>
{
var container = new UnityContainer();
RegisterTypes(container);
return container;
});
/// <summary>
/// Gets the configured Unity container.
/// </summary>
public static IUnityContainer GetConfiguredContainer()
{
return container.Value;
}
#endregion
}
So that allowed me to access the Unity container directly to obtain named type instances.
var footballer1 = UnityConfig.GetConfiguredContainer().Resolve<IFootballer>("Attacker");
var footballer2 = UnityConfig.GetConfiguredContainer().Resolve<IFootballer>("Defender");