Constructor Dependency injection in the model - is this possible in MVC?

106 views
Skip to first unread message

Jason Horne

unread,
Feb 19, 2015, 6:31:32 PM2/19/15
to glasssite...@googlegroups.com
Hi,

I'm pretty new to MVC so it could be a noob question. In web forms I would use constructor dependency injection in my models like the below:

    [SitecoreType(AutoMap = true)]
    public class Article
    {
        private readonly ICommonService _commonService;

        public Article(ICommonService commonService)
        {
            _commonService = commonService;
        }

        [SitecoreId]
        private Guid Id { get; set; }

        public string Title { get; set; }

        [SitecoreIgnore]
        public string GetTestString
        {
            get { return _commonService.GetTestString(); }
        }
    }

The idea here is to move the logic into services and keep loosely coupled with DI. So Glass provides raw Sitecore data then the services help manipulate that data or pull in extra data to complete the model.

Is it possible to have a view rendering with a reference to the model which resolves the DI and the model is ready to use?:
@inherits Glass.Mapper.Sc.Web.Mvc.GlassView<Article>

Currently when i attempt this I get 

No parameterless constructor defined for this object


I can get the above working by using a controller and passing the dependency into the model via the controller.

Is it possible to have this work in a simple view rendering to cut out the creation of a controller view for model that requires some logic?

Cheers,
Jason 





Jason Horne

unread,
Feb 20, 2015, 3:16:08 AM2/20/15
to glasssite...@googlegroups.com
Reply all
Reply to author
Forward
0 new messages