Thursday, April 27, 2017
Creating an IOC Container for ASP.NET Core
I recently added support for ASP.NET Core to my Tact.NET IOC Container, and I thought that I would share some of the interesting requirements I discovered while doing so. I had originally expected the default ASP.NET Core container would follow the same rules as the official Microsoft Unity container, but that turned out not to be the case!
1) Register is first in win.
The Unity container was last in win, and it would completely disregard the original registration. With ASP.NET Core you need to preserve the original registration and then treat all subsequent registrations as addition registrations that will only be resolved when ResolveAll is invoked, similar to keyed registrations in Unity. Which brings us to our next difference...
public class RegisterIsFirstInWinTests
{
[Fact]
public void Unity()
{
var log = new EmptyLog();
using (var container = new TactContainer(log))
{
container.RegisterSingleton<IExample, ExampleA>();
container.RegisterSingleton<IExample, ExampleB>();
var example = container.Resolve<IExample>();
Assert.IsType<ExampleB>(example);
}
}
[Fact]
public void AspNetCore()
{
var log = new EmptyLog();
using (var container = new AspNetCoreContainer(log))
{
container.RegisterSingleton<IExample, ExampleA>();
container.RegisterSingleton<IExample, ExampleB>();
var example = container.Resolve<IExample>();
Assert.IsType<ExampleA>(example);
}
}
public interface IExample
{
string Name { get; }
}
public class ExampleA : IExample
{
public string Name => nameof(ExampleA);
}
public class ExampleB : IExample
{
public string Name => nameof(ExampleB);
}
}
2) ResolveAll includes single registrations.
Unity has the concept of keyed registrations, where you can register the same type multiple times with distinct keys (strings) and then resolve them individually by key or as an IEnumerable with ResolveAll. In ASP.NET Core there is no concept of keyed registration, and ResolveAll will return all registrations made for a given type. This means that registering a single type will cause ResolveAll to return an IEnumerable with one value.
public class ResolveAllIncludesSingleRegistrations
{
[Fact]
public void Unity()
{
var log = new EmptyLog();
using (var container = new TactContainer(log))
{
container.RegisterSingleton<IExample, ExampleA>();
container.RegisterSingleton<IExample, ExampleB>();
var examples = container.ResolveAll<IExample>();
Assert.Equal(0, examples.Count());
}
}
[Fact]
public void AspNetCore()
{
var log = new EmptyLog();
using (var container = new AspNetCoreContainer(log))
{
container.RegisterSingleton<IExample, ExampleA>();
container.RegisterSingleton<IExample, ExampleB>();
var examples = container.ResolveAll<IExample>();
Assert.Equal(2, examples.Count());
}
}
public interface IExample
{
string Name { get; }
}
public class ExampleA : IExample
{
public string Name => nameof(ExampleA);
}
public class ExampleB : IExample
{
public string Name => nameof(ExampleB);
}
}
3) Generic resolution is required.
This was a neat feature that I had not used before! You can register generic types without any generic parameters, and then the container will fill in the generic parameters based on the resolve request. So, for example, I could register IRepository<> to type DataRepository<>, and then when I call container.Resolve<IRepository<User>>, the IOC container will automatically try to construct a DataRepository<User>
public class TactContainerTests
{
[Fact]
public void GenericResolution()
{
var log = new EmptyLog();
using (var container = new TactContainer(log))
{
container.RegisterSingleton(typeof(IRepository<>), typeof(Repository<>));
var userRepository = container.Resolve<IRepository<User>>();
Assert.IsType<Repository<User>>(userRepository);
}
}
public interface IRepository<T>
{
string ClassName { get; }
string GenericName { get; }
}
public class Repository<T> : IRepository<T>
{
public string ClassName => nameof(Repository<T>);
public string GenericName => typeof(T).Name;
}
public class User
{
}
}
4) You have to convert IServiceCollection to your container.
I like how the new .NET separates their service registration from the container itself. In your ASP.NET Core wire up you will work with an IServiceCollection, which will then be converted into a container after you are done filling in your registrations. This means that if you want to create your own container, you will need to map the service collection into your container.
Enjoy,
Tom
33 comments:
You’ve written a really great article here. Your writing style makes this material easy to understand.. I agree with some of the many points you have made. Thank you for this is real thought-provoking content.
Reply DeleteMSBI Online Training
MSBI Online Certification
Learn MSBI Course
I understand the codings for ASP.NET and it is in very simple manner and understandable for beginners too.
Reply DeletePython Training in Chennai | Certification | Online Course Training | Python Training in Bangalore | Certification | Online Course Training | Python Training in Hyderabad | Certification | Online Course Training | Python Training in Coimbatore | Certification | Online Course Training | Python Training in Online | Certification | Online Course Training
Thanks for sharing this with us......this is really appreciating.
Reply DeleteBSc Time Table
BSc 1st year time table
BSc 2nd year time table
BSc 3rd year time table
It's really nice and meanful. it's really cool blog. Linking is very useful thing. You have really helped lots of people who visit blog and provide them useful information.
Reply Delete한국야동
This post is disseminating valuable information to people who are most concerned of the following issues being targeted by this site. Many certainly will keep coming back to check out updated posts.
Reply Delete안전놀이터 모음
Nice Information I read this hope you share another ane thanks.here, is Nora our organization are providing security software and build your website and promote your brand you can go and read this.
Reply Deletecrypto wallet|
exodus wallet|
metamask wallet|
trezor wallet|
phantom wallet|
thanks for the information, very useful
Reply Deletesocial media management
This comment has been removed by the author.
Reply DeleteWell-written information. Very impressive and to the point
Reply DeleteHave a look at my new blog Windows 11 Activator Crack 2023
This comment has been removed by the author.
Reply DeleteThe Evening Desert Safari tour is an activity that one should not miss out on especially if you are on your Dubai tour, this is an adventurous activity.
Reply DeleteThis comment has been removed by the author.
Reply DeleteThis comment has been removed by the author.
Reply DeleteEmbarking on your cryptocurrency journey with Trezor begins at trezor.io/start, the official portal designed to guide you through the setup and secure management of your digital assets.
Reply DeleteVisit trezor.io/start | to securely set up your Trezor hardware wallet. Follow an easy step-by-step guide to install Trezor Suite, back up your recovery seed, and protect your crypto assets from online threats. Start your journey to secure cryptocurrency storage today.
Reply DeleteBuy Luxury Villa in Goa | Best Sea View Villas for Sale
Reply DeleteDiscover the best luxury villas for sale in Goa with NYSA Luxury Homes. From elegant sea view villas to premium Goa property for sale, we offer handpicked listings that redefine comfort and exclusivity. Whether you're looking to buy a luxury villa in Goa or invest in a high-end retreat, our curated selection ensures exceptional living and value. Explore luxury sea view villas for sale in Goa today and find your perfect escape in paradise with NYSA – your trusted partner for premium real estate in Goa.
Buy Luxury Villa in Goa
best Luxury Villas for sale in goa
Villas developer in goa
luxury villas in goa to buy
Experience luxury living at its finest with Como Residences , offering stunning views and elegant design. Como Residences blends modern lifestyle with comfort in every detail.
Reply DeleteDiscover luxury living at its best with Damac Casa , offering elegant homes and world-class amenities in a prime location.
Reply DeleteExperience thrilling rides and racing fun at Ferrari World , the famous Ferrari-themed park in Abu Dhabi.
Reply DeleteDiscover the charm of waterfront living at damac lagoons , where beautiful homes meet stunning crystal lagoons. Perfect for a peaceful family lifestyle!
Reply DeleteA stunning waterfront community, Damac Bay 2 by Cavalli blends luxurious design and resort-style amenities for a relaxed yet upscale lifestyle.
Reply DeleteDiscover luxury at Atlantis the Palm , a stunning resort on Dubai's famous Palm Jumeirah. Atlantis The Palm offers world-class dining, adventure, and breathtaking ocean views.
Reply DeleteExperience thrilling virtual adventures at VR Park Dubai , where reality and imagination blend for ultimate fun.
Reply DeleteA world-famous man-made island, Palm Jumeirah is shaped like a palm tree and offers luxury living, shopping, and stunning beach resorts.
Reply DeleteStep into a world of lights, art, and imagination at the mesmerizing Aya Universe , a top attraction in Dubai for all ages.
Reply DeleteA magical water and light performance, the Dubai Fountain show show dances to music near Burj Khalifa, offering a breathtaking view every evening.
Reply DeleteExperience the thrill of skydiving indoors at iFly Dubai , where you can float and fly safely in a wind tunnel. iFly Dubai offers fun for all ages in a unique adventure setting.
Reply DeleteA magical family spot, Dubai Garden Glow in the heart of the city lights up evenings with glowing art and themed zones. Perfect for kids and adults alike!
Reply DeleteExperience the thrill of Skiing at Ski Dubai , the Middle East's first indoor ski resort.
Reply DeleteWhen it comes to protecting cryptocurrency, the Trezor Hardware Wallet is a trusted solution used by millions worldwide. To ensure your device is set up safely, always start at Trezor.io/start—the official guide from Trezor. Here, you’ll find the right tools, verified software, and step-by-step instructions to initialize your wallet without risk. Trezor.io/start | Trezor.io/start | Ledger Live Wallet |Trezor.io/start
Reply Delete| uphold login |
Reply Deletecoinbase pro login |
ndax login |
Modal receh meledak jadi sensasional di dewapoker link alternatif . Klik daftar, aktifkan bonus, lalu spin Sweet Bonanza hari ini di main dominobet asia !
Reply DeleteAccess your USAA Bank account easily through the USAA Bank Login (**) page. Securely access your crypto portfolio with the BlockFi Login (**). The Coinsquare Login (**) portal lets you buy, sell, and track your portfolio anytime with confidence and ease. Metamask Login (**) allows users to securely access decentralized applications (dApps) using their crypto wallet. Netcoins Login (**) provides users with secure access to their cryptocurrency trading accounts.
Reply Delete