If you are creating EPiServer Commerce users from a scheduled task, you might encounter an "Object reference not set to an instance of an object" error when you call the SaveChanges() on your CustomerContact object.

Fortunately, there is a simple solution to this error. The solution is quite obvious, but I spent too much time finding the solution myself. I thought it would be nice to share the solution in a small blog post :)

The reason you get the error, is that you do not have a DataContext when you are running your scheduled task. Add the following lines in the start of you scheduled task code, and you will be able to create users without any errors:

if (DataContext.Current == null)
{
string connectionstring = ConfigurationManager.ConnectionStrings["EcfSqlConnection"].ConnectionString;
DataContext.Current = new DataContext(connectionstring);