jdraper3
jdraper3

Reputation: 116

StructureMap - NullReferenceException

I'm new to IoC and I'm trying to get started using StructureMap, but it is throwing a NullReferenceException when I try to get an object instance. Here's my init code:

ObjectFactory.Initialize(x =>
{
    x.ForRequestedType<IRepository<Customer>>().TheDefaultIsConcreteType<EFRepository<Customer>>();             
    x.ForRequestedType<ICustomerManager>().TheDefaultIsConcreteType<CustomerManager>();
});

The ICustomerManager uses ctor injection and receives an IRepository:

public class CustomerManager : ICustomerManager
{
  IRepository<Customer> _repository;
  public CustomerManager(IRepository<Customer> repository)
  {
    _repository = repository;
  }

  public Customer GetCustomerById(int id)
  {
    return _repository
             .With(c => c.PhoneNumbers)
             .FirstOrDefault<Customer>(c => c.Id == id);
  }

  public IEnumerable<Customer> GetCustomersByName(string lastName, string firstName, string middleName)
  {
    return _repository.Query(new CustomerMatchesName(lastName, firstName, middleName));
  }
}

Then in my service layer code, this line throws the exception:

var manager = ObjectFactory.GetInstance<ICustomerManager>();

I really have no idea where to start debugging this, being so new to the concepts in general. Any ideas on what could be going wrong in such a simple scenario?

Upvotes: 1

Views: 1356

Answers (1)

Chris Marisic
Chris Marisic

Reputation: 33098

You most likely are getting an exception that StructureMap can't build an object, which causes a cascading exception of a null reference that has eaten the real exception.

The best solution for debugging these scenarios is turning on catch all exceptions, Ctrl+Alt+E and mark to catch all thrown exceptions.

The next tool to goto is StructureMap provides a utility method ObjectFactory.WhatDoIHave();

In all of my projects I have in my initialization code in Application_Start (I only do asp.net) I have the following code block

#if DEBUG
    string path = Server.MapPath("~/myproj.WhatDoIHave.txt");
    string whatDoIHave = ObjectFactory.WhatDoIHave();
    File.WriteAllText(path, whatDoIHave);
#endif

This output has offered me help innumerable times. Learning to read this file will let you troubleshoot basically any registration problems you have because you'll be able to see exactly what you do, and don't have.

Most times with StructureMap you end up troubleshooting what you DON'T have. Which usually boils down to needing to register a complex type that StructureMap can't satisfy.

Upvotes: 4

Related Questions