-
Jul 4th, 2018, 06:54 PM
#1
Thread Starter
Registered User
Null Form in casting with ServiceProvider
I have the code below. the form return a null. What code should I write to prevent it?
Code:
private static IServiceProvider ServiceProvider { get; set; }
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
var services = new ServiceCollection();
services.AddScoped<IEntityService, IEntityService>();
ServiceProvider = services.BuildServiceProvider();
var form = (MainForm)ServiceProvider.GetService(typeof(ainForm));
Application.Run(form);
}
-
Jul 6th, 2018, 03:33 AM
#2
Re: Null Form in casting with ServiceProvider
Well firstly you should be debugging ainForm and finding out why its returning null.
If there is a legitimate reason why it could return null then you should add some handling around the application.Run command and send a message to the user telling them the application couldn't be started
Please Mark your Thread "Resolved", if the query is solved & Rate those who have helped you
-
Jul 6th, 2018, 03:38 AM
#3
Re: Null Form in casting with ServiceProvider
Firstly, this:
isn't a meaningful statement. It's ServiceProvider.GetService that is returning null. That method is supposed to return a form but it doesn't.
What exactly is 'ainForm'? Should that actually be 'MainForm'? You are supposed to have registered the type you're passing somewhere and specified what should be returned in that case. I'd say that you probably haven't registered that type.
-
Jul 8th, 2018, 07:06 PM
#4
Thread Starter
Registered User
Re: Null Form in casting with ServiceProvider
oh sorry: it should be :
var form = (MainForm)ServiceProvider.GetService(typeof(MainForm));
where "MainForm" is the MainForm.cs of my project.
-
Jul 9th, 2018, 04:48 AM
#5
Re: Null Form in casting with ServiceProvider
I'm not sure what service provider class you are using but, basically, you have to register all your services with it somewhere. Exactly where and how will depend on the implementation. You should read the documentation for the provider you're using to see how it's done. In general, you specify a type that you can request and (usually) another type or an object that will be returned when you request it. Mostly, the type you request is an interface and you register a class that implements that interface to provide that service when requested. That allows you to, for instance, provide a different implementation of the interface for unit testing than in a release. In your case, you probably want to specify that a specific instance of MainForm provides the service for the type MainForm, so you would need to learn how to do that. That means that you can access that specific instance anywhere via the service provider.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|