how can IEventAggregator not be used by constructor injection? #2540
-
A real-time communication program defines a static method to obtain data in real time: public class CommonState
{
private static IEventAggregator _eventAggregator;
public CommonState(IEventAggregator eventAggregator)
{
_eventAggregator = eventAggregator;
}
public static bool isRunning = true;
static Task mainTask = null;
private static readonly HttpClient _httpClient = new HttpClient();
private static readonly string _urlGet = "http://127.0.0.1:52335/api/RedisRealData/";
//private static IEventAggregator _eventAggregator;
public static void Start()
{
isRunning = true;
mainTask = Task.Run(async () =>
{
var varList = new List<string> { "CsSs", "CsLl", "CsCod" };
while (isRunning)
{
await Task.Delay(3000);
foreach (var item in varList)
{
var response = await _httpClient.GetAsync(_urlGet+item);
var json = await response.Content.ReadAsStringAsync();
var energyList = JsonConvert.DeserializeObject<string>(json);
try
{
RealDataContent mmt = new RealDataContent
{
VarName = item,
VarValue = energyList
};
_eventAggregator.GetEvent<RealDataHttpEvent>().Publish(mmt);
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
}
});
}
public static void Stop()
{
isRunning = false;
mainTask.ConfigureAwait(true);
}
} In app.xaml.cs, to control the process: protected override void OnStart()
{
CommonState.Start();
}
protected override void OnSleep()
{
CommonState.Stop();
}
protected override void OnResume()
{
CommonState.Start();
} You need to add type parameters to the IEventAggregator class constructor to use dependency injection. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
maybe don't use static method, just use singleton, I'm not sure if it's appropriate |
Beta Was this translation helpful? Give feedback.
-
based on the code that you've shared, I would suggest adding the IEventAggregator as a parameter of your CommonState.Start. protected override void OnStart()
{
var ea = Container.Resolve<IEventAggregator>();
CommonState.Start(ea);
} If that is not an option because you absolutely have to use this from a completely static context where you cannot so easily access the container, and you have no other option other than to use a Service Locator pattern, then as long as you're using Prism 8+ you can use the ContainerLocator. public void Start()
{
var ea = ContainerLocator.Container.Resolve<IEventAggregator>();
} |
Beta Was this translation helpful? Give feedback.
based on the code that you've shared, I would suggest adding the IEventAggregator as a parameter of your CommonState.Start.
If that is not an option because you absolutely have to use this from a completely static context where you cannot so easily access the container, and you have no other option other than to use a Service Locator pattern, then as long as you're using Prism 8+ you can use the ContainerLocator.