999cm999 999cm999 - 3 months ago 8
C# Question

Using non-static code with static main method

I'm having trouble with getting my static main method to play nicely with my backend code.

Here's the backend stuff:

public interface ITicketGenerationService
{
string CreateTicket(DateTime begin, DateTime end);
}

public class TicketGenerationService : ITicketGenerationService
{
public static IRepository<Ticket> Repository { get; set; }

public TicketGenerationService(IRepository<Ticket> repository)
{
Repository = repository;
}

public string CreateTicket(DateTime begin, DateTime end)
{
//do stuff with Repository
//return status string to Main method
}

}


Here's where my console application begins:

public class TicketMain
{
public ITicketGenerationService TicketGenerationService { get; set; }

static void Main(string[] args)
{
var priorityOneTickets = TicketGenerationService.CreateTicket(begin, end);
}
}


So I initially get this error:


An object reference is required for the non-static field, method, or
property 'TicketMain.TicketGenerationService'


If I change CreateTicket to static, I get another error:


TicketGenerationService does not implment interface member
ITicketGenerationService.CreateTicket(DateTime, DateTime).
ITicketGenerationService.CreateTicket(DateTime, DateTime) cannot
implement an interface member because it is static.


If I try to add this:


var ticketingService = new TicketGenerationService();


to the main method, I'm afraid that will mess with my dependency injection(autofac).

I understand the errors, but I can't make everything static, and I'm afraid if I start instantiating, I'll lose all my data I gain via dependency injection.

Is there anyway around this?

Thanks!

Answer

It's not the TicketGenerationService.CreateTicket method that the error is referring to, it's your TicketGenerationService property in the TicketMain class.

You just need to change your property to static:

public static ITicketGenerationService TicketGenerationService { get; set; }