“Get out form smog” – dependency injection

Get out from smog – part V

Today post will be about depencendy injection.And run all the written functions as a whole. Uses for this Autofac and Autofac.Mvc – to inject depencencies on the contollers.

I created class to register depencencies.

public class AutofacConfig
{
    public static void ConfigureAutofac()
    {
        var builder = new ContainerBuilder();
        builder.RegisterControllers(typeof(MvcApplication).Assembly);
        builder.RegisterType<GetInfoAboutLongitude>().As<IGetInfoAboutCoordiateStation>();
        builder.RegisterType<ParseJsonToList>().As<IParseJsonToListAboutMeasureStation>();
        builder.RegisterType<ReturnNearestStationsIn100Km>().As<IReturnNearestStation>();
        var container = builder.Build();
        DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
    }
}

We register the interface to a particular class and the ability to inject into the contoller.

Now inject interface into the contoller constructor.

private readonly IParseJsonToListAboutMeasureStation _parseJsonToListAboutMeasureStation;
private readonly IGetInfoAboutCoordiateStation _getInfoAboutCoordiateStation;
private readonly IReturnNearestStation _returnNearestStation;

public HomeController(IParseJsonToListAboutMeasureStation parseJsonToListAboutMeasureStation, IGetInfoAboutCoordiateStation getInfoAboutCoordiateStation,
    IReturnNearestStation returnNearestStation)
{
    _parseJsonToListAboutMeasureStation = parseJsonToListAboutMeasureStation;
    _getInfoAboutCoordiateStation = getInfoAboutCoordiateStation;
    _returnNearestStation = returnNearestStation;
}

Thanks to this magician we can now call our functions like this:

public ActionResult Coordinate(string lat,string lon)
{
    var latitudes = double.Parse(lat, CultureInfo.InvariantCulture);
    var longitudes = double.Parse(lon, CultureInfo.InvariantCulture);
    var model = _parseJsonToListAboutMeasureStation.ParseStringToArray();
    model = _getInfoAboutCoordiateStation.GetLongitudeAfterAdress(model);
    model = _returnNearestStation.ReturnNearestStation(model, latitudes, longitudes);
    return View();
}

Thanks to this, we have received the nears measuring station within a radius of 100 km from the user’s location.

getoutfromsmog

In the next step I will try to find the cleanest air among from this stactions.

Link to the project: HERE

Leave a Reply

Your email address will not be published. Required fields are marked *