-
Notifications
You must be signed in to change notification settings - Fork 9.8k
/
EntityFrameworkCoreXmlRepository.cs
83 lines (75 loc) · 3.08 KB
/
EntityFrameworkCoreXmlRepository.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using Microsoft.AspNetCore.DataProtection.Repositories;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace Microsoft.AspNetCore.DataProtection.EntityFrameworkCore
{
/// <summary>
/// An <see cref="IXmlRepository"/> backed by an EntityFrameworkCore datastore.
/// </summary>
public class EntityFrameworkCoreXmlRepository<TContext> : IXmlRepository
where TContext : DbContext, IDataProtectionKeyContext
{
private readonly IServiceProvider _services;
private readonly ILogger _logger;
/// <summary>
/// Creates a new instance of the <see cref="EntityFrameworkCoreXmlRepository{TContext}"/>.
/// </summary>
/// <param name="services"></param>
/// <param name="loggerFactory">The <see cref="ILoggerFactory"/>.</param>
public EntityFrameworkCoreXmlRepository(IServiceProvider services, ILoggerFactory loggerFactory)
{
if (loggerFactory == null)
{
throw new ArgumentNullException(nameof(loggerFactory));
}
_logger = loggerFactory.CreateLogger<EntityFrameworkCoreXmlRepository<TContext>>();
_services = services ?? throw new ArgumentNullException(nameof(services));
}
/// <inheritdoc />
public virtual IReadOnlyCollection<XElement> GetAllElements()
{
using (var scope = _services.CreateScope())
{
var context = scope.ServiceProvider.GetRequiredService<TContext>();
// Put logger in a local such that `this` isn't captured.
var logger = _logger;
return context.DataProtectionKeys.AsNoTracking().Select(key => TryParseKeyXml(key.Xml, logger)).ToList().AsReadOnly();
}
}
/// <inheritdoc />
public void StoreElement(XElement element, string friendlyName)
{
using (var scope = _services.CreateScope())
{
var context = scope.ServiceProvider.GetRequiredService<TContext>();
var newKey = new DataProtectionKey()
{
FriendlyName = friendlyName,
Xml = element.ToString(SaveOptions.DisableFormatting)
};
context.DataProtectionKeys.Add(newKey);
_logger.LogSavingKeyToDbContext(friendlyName, typeof(TContext).Name);
context.SaveChanges();
}
}
private static XElement TryParseKeyXml(string xml, ILogger logger)
{
try
{
return XElement.Parse(xml);
}
catch (Exception e)
{
logger?.LogExceptionWhileParsingKeyXml(xml, e);
return null;
}
}
}
}