Question

I need to avoid parameters to create an Helper so I use AutoFac, but I'm not able to do it:

public class PTDistrictHelpers
{
    private readonly IPTDistrictService _ptDistrictService;

    public PTDistrictHelpers(IPTDistrictService ptDistrictService)
    {
        _ptDistrictService = ptDistrictService;
    }

    public IEnumerable<SelectListItem> DropDownList(int selectedValue = GlobalConstants.DROPDOWNLIST_NO_SELECTED_VALUE)
    {
        var ptDistrictsDto = _ptDistrictService.ListAll();
        var ptDistrictsViewModel = Mapper.Map<IList<PTDistrictDto>, IList<PTDistrictViewModel>>(ptDistrictsDto);

        var ptDistrictsList = ptDistrictsViewModel.Select(district =>
            new SelectListItem
            {
                Value = district.Id.ToString(),
                Text = district.Name,
                Selected = (district.Id == selectedValue)
            });

        return ptDistrictsList;
    }
}

In the AutoFac Config I have:

public class AutofacConfig
{
    public static void RegisterDependencies()
    {
        var builder = new ContainerBuilder();
        builder.RegisterControllers(Assembly.GetExecutingAssembly());
        builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

        // PTDistrict Helpers
        builder.RegisterType<PTDistrictHelpers>()
            .As<PTDistrictHelpers>()
            .InstancePerHttpRequest();

        // PTDistrict Interface registration
        builder.RegisterType<PTDistrictService>()
            .As<IPTDistrictService>()
            .InstancePerHttpRequest();
     }
 }

In the Controller when I try to create a new PTDistrictHelpers I get the error "does not contain a constructor that takes 0 argument".

var ptDistrictList = new PTDistrictHelpers().DropDownList();
Was it helpful?

Solution

Somewhere you also need to register an IPTDistrictService so Autofac can populate the helper constructor.

I don't know if you're really trying to new-up a helper or if that's just for example, but the helper class you posted doesn't have a no-parameter constructor so that last code snippet wouldn't compile.

Your controller should take in a helper class as a constructor parameter and let Autofac do the work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top