Search code examples
c#autofac

Creating/Resolving a list of objects using Autofac


I'm learning IoC and Autofac so my question is rather basic but I couldn't find satisfactory answer. I have these test classes:

DataModel.cs

public class DataModel : IDataModel
{
    public int PosX { get; set; }
    public int PosY { get; set; }
    public string Name { get; set; }

    public DataModel(int posx, int posy, string name)
    {
        PosX = posx;
        PosY = posy;
        Name = name;
    }
    public void WriteName()
    {
        Console.WriteLine($"Hello, my name is \"{Name}\". Nice to meet you!");
    }
    public void WritePosition()
    {
        Console.WriteLine($"\"{Name}\": Position of X axis is {PosX} and position of Y axis is {PosY}");
    }

}

BusinessLogic.cs

public class BusinessLogic : IBusinessLogic
{
    ILogger _logger;
    IList<IDataModel> _dataModels;
    public BusinessLogic(ILogger logger, IList<IDataModel> dataModels)
    {
        _logger = logger;
        _dataModels = dataModels;
    }

    

    public void ProcessData()
    {

        
        _logger.Log("Starting the processing of devices data.");
        _logger.Log("Processing the data...");
        foreach (var model in _dataModels)
        {
            model.WriteName();
            model.WritePosition();
        }
        
        _logger.Log("Finished processing the data.");
    }
}

Now as you can see ctor of BusinessLogic needs collection of IDataModel. The question is how do I create List of Interfaces stored in the container to achieve something like this:

for(int x = 0; x <=7; x++)
{
  for(int y = 0; y <= 7; y++)
  {
    list.Add(new DataModel(x,y,$"Object {x}{y}"));
  }
}

Maybe I got the whole idea wrong. I am grateful for every answer. Thanks!


Solution

  • Note that IList<IDataModel> dataModels is not a service, to be resolved. I'm not sure that it is the best way, however you have to create a service (for example IDataInitializer) providing a method or an object for IList<IDataModel> dataModels, register it on IServiceCollection or IOC container in Startup.cs and then it can be resolved in other services and classes.

    Here is an example:

    public interface IDataInitializer
    {
        IList<IDataModel> GetDataModel();
    }
    public class DataInitializer : IDataInitializer
    {
        private IList<IDataModel> _dataModels;
        public DataInitializer()
        {
            for (int x = 0; x <= 7; x++)
            {
                for (int y = 0; y <= 7; y++)
                {
                    _dataModels.Add(new DataModel(x, y, $"Object {x}{y}"));
                }
            }
        }
        public IList<IDataModel> GetDataModel()
        {
            return _dataModels;
        }
    
    }
    
    public IServiceProvider ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton<IDataInitializer>(new DataModel());
    }