Using Internal Properties in RazorEngine

六月ゝ 毕业季﹏ 提交于 2021-01-27 03:54:37

问题


Our domain model properties are all "Internal" to protect the BDD approach we have taken. I really like making everything internal.

Recently I am trying to get the RazorEngine to process a template using one of these domain models with internal members. When it compiles, I get the error: .Attendee.FirstName' is inaccessible due to its protection level

I tried adding this line [assembly: InternalsVisibleTo("RazorEngine")] to the AssemblyInfo.cs of my domain model, but it doesnt seem to help.

How can I make my internal properties visible to the RazorEngine within the same project.

Code

public class Attendee : AggregateRoot {
    protected internal virtual new long Id { get; protected set; }
    protected internal virtual Event Event { get; protected set; }
    protected internal virtual bool? Online { get; protected set; }
    protected internal virtual string FirstName { get; protected set; }
    protected internal virtual string LastName { get; protected set; }
    protected internal virtual string Email { get; protected set; }
    protected internal virtual string Affiliation { get; protected set; }
    protected internal virtual string MeetingPassword { get; protected set; }
    protected internal virtual decimal AmountPaid { get; protected set; }
    protected internal virtual DateTime DateRegistered { get; protected set; } 

    public virtual void SendEmail() {

                var assembly = Assembly.GetExecutingAssembly();
                var stream = assembly.GetManifestResourceStream("VirtualAcademy.Domain.Email.RegistrationConfirmation.cshtml");
                var reader = new StreamReader(stream);
                var template = reader.ReadToEnd();                 
                Engine.Razor.RunCompile(template, "key", null, this);
     }

CSHTML FIle

@model VirtualAcademy.Domain.Attendee

<html>
<body style="font: 12px arial, sans-serif">
    <div>
        <span id="SalutationLabel">Hello @Model.FirstName @Model.LastName,</span>

回答1:


Unfortunately you can't do that...

@Model is just a public property of WebViewPage< TModel > so InternalsVisibleTo makes no difference

I suggest you create a ViewModel for your view.
(Maybe with a T4 template you can generate classes for your internal Models)

Now,if you are willing to lose type safety you can write an extension method and access the value using reflection




回答2:


InternalsVisibleTo attribute expects the name of the assembly not the class name or namespace. So you need to change it to following.

[InternalsVisibleTo("System.Web.Mvc")]



回答3:


Have a read at Microsoft. There could be issues with strong naming or StrongNameIdentityPermission class



来源:https://stackoverflow.com/questions/42264992/using-internal-properties-in-razorengine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!