very new to Structure-Map. trying to figure it out how it works and how can i benefit from it.
i have got this so far..
Global.asax.cs:
IContainer container = new Container(x =>
{
x.For<IControllerActivator>().Use
<StructureMapControllerActivator>();
x.For<IUserRepo>().Use<UserRepo>();
});
DependencyResolver.SetResolver(new StructureMapDependencyResolver(container));
StructureMapControllerActivator:
public class StructureMapControllerActivator : IControllerActivator
{
private readonly IContainer _container;
public StructureMapControllerActivator(IContainer container )
{
this._container = container;
}
public IController Create(RequestContext requestContext, Type controllerType)
{
return _container.GetInstance(controllerType) as IController;
}
}
StructreMapDependencyResolver:
private readonly IContainer _container;
public StructureMapDependencyResolver(IContainer container )
{
this._container = container;
}
public object GetService(Type serviceType)
{
object instance = _container.TryGetInstance(serviceType);
if(instance == null && !serviceType.IsAbstract)
{
_container.Configure(c => c.AddType(serviceType,serviceType));
instance = _container.TryGetInstance(serviceType);
}
return instance;
}
public IEnumerable<object> GetServices(Type serviceType)
{
return _container.GetAllInstances(serviceType).Cast<object>();
}
}
My AccountController:
public class AccountController : Controller
{
private readonly IUserRepo _userRepo;
private AccountController()
{
_userRepo = ObjectFactory.GetInstance<IUserRepo>();
}
public ActionResult Login()
{
return View();
}
}
Error Code & Description:
StructureMap Exception Code: 202 No Default Instance defined for PluginFamily MBP_Blog.Controllers.AccountController MBP-Blog, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
I have a Interface Name : IUserRepo and a repository Name: UserRepo
please help as I try to google but dint find any solution within first 3 pages.
New error after using @Martin's code:
StructureMap Exception Code: 180 StructureMap cannot construct objects of Class MBP_Blog.Controllers.AccountController, MBP-Blog, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null because there is no public constructor found.