Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using Autofac;
- namespace TestAutoFac
- {
- class Program
- {
- static void Main(string[] args)
- {
- var builder = new ContainerBuilder();
- // Register our types with AutoFac
- // House is a singleton because whatever.
- builder.RegisterType<House>().SingleInstance();
- // Register implementations as the interface type.
- builder.RegisterType<SmallBedroom>().As<IBedroom>();
- builder.RegisterType<MasterBedroom>().As<IBedroom>();
- builder.RegisterType<Kitchen>().As<IKitchen>();
- builder.RegisterType<Bathroom>().As<IBathroom>();
- var container = builder.Build();
- // Resolve the house.
- // Note: no parameters passed despite house constructor requiring 3 parameters.
- // Parameters will be resolved via registered types.
- // IEnumerable parameters will contain each unique type resolution of parameter (i.e., IEnumerable<IBathroom> will contain one SmallBedroom and one MasterBedroom)
- House h = container.Resolve<House>();
- // Output:
- // Kitchen
- // Bathroom
- // MasterBedroom
- // SmallBedroom
- Console.WriteLine(h.Kitchen.GetType().Name);
- Console.WriteLine(h.Bathroom.GetType().Name);
- foreach (IBedroom bedroom in h.Bedrooms)
- {
- Console.WriteLine(bedroom.GetType().Name);
- }
- Console.ReadLine();
- }
- }
- public class House
- {
- public IKitchen Kitchen { get; private set; }
- public IBathroom Bathroom { get; private set; }
- public List<IBedroom> Bedrooms { get; private set; }
- public House(IKitchen kitchen, IBathroom bathroom, IEnumerable<IBedroom> bedrooms)
- {
- Kitchen = kitchen;
- Bathroom = bathroom;
- Bedrooms = bedrooms.ToList();
- }
- }
- public interface IKitchen
- {
- }
- public interface IBedroom
- {
- }
- public interface IBathroom
- {
- }
- public class Kitchen : IKitchen
- {
- }
- public class Bathroom : IBathroom
- {
- }
- public class SmallBedroom : IBedroom
- {
- }
- public class MasterBedroom : IBedroom
- {
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement